-
Notifications
You must be signed in to change notification settings - Fork 1
/
device.js
180 lines (150 loc) · 4.54 KB
/
device.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
// Setup for all libraries
const axios = require('axios');
const admin = require('firebase-admin');
const uuid = require('uuid-v4');
const Mqtt = require('azure-iot-device-mqtt').Mqtt;
const DeviceClient = require('azure-iot-device').Client;
const Message = require('azure-iot-device').Message;
const NodeWebcam = require( "node-webcam" );
const fs = require('fs');
var FormData = require('form-data');
const socketIOClient = require('socket.io-client');
const ENDPOINT = "http://fruitvisionserver.herokuapp.com";
// create webcam
const opts = {
width: 500,
height: 300,
quality: 50,
frames: 60,
delay: 0,
saveShots: true,
output: "jpeg",
device: false,
callbackReturn: "location",
verbose: false
};
const Webcam = NodeWebcam.create( opts );
// get device info file (or create it if dne)
let deviceInfo = undefined;
try {
deviceInfo = require('./device.json');
init();
}
catch(error) {
console.log("Generating device config...")
json = {
id: uuid(),
status: "pairing",
ownerId: undefined,
name: "Fruit Monitor"
};
fs.writeFile('device.json', JSON.stringify(json), 'utf8', ()=>{
console.log("Device config generated!")
deviceInfo = require('./device.json');
init();
});
}
// iot hub connection string
// const connectionString = 'HostName=FruitHub.azure-devices.net;DeviceId=MyNodeDevice;SharedAccessKey=ZIj/h8x4qjOgwT87zvYTz528usDT7OeiN8o4IGKbT9s=';
const connectionString = 'HostName=FruitVision2.azure-devices.net;DeviceId=MyNodeDevice;SharedAccessKey=V+OufF7sOXhhx1jwT2M3cHeDAhIfay7E/sj10TeeavY=';
// iot hub client
const client = DeviceClient.fromConnectionString(connectionString, Mqtt);
/**
* Method to send photo to Azure to be analyzed
* @param url url of the photo
*/
async function analyze(url) {
var data = new FormData();
data.append('image file', fs.createReadStream(url));
var config = {
method: 'post',
url: 'https://fruitvision.cognitiveservices.azure.com/customvision/v3.0/Prediction/a16bd1d4-1eec-495e-82d6-0edbf005757d/classify/iterations/Iteration2/image',
headers: {
'Prediction-Key': 'ff56c613f1ae48bba40bc89bbfb3fc9a',
'Content-Type': 'application/octet-stream',
...data.getHeaders()
},
data : data
};
axios(config)
.then(function (response) {
// console.log(JSON.stringify(response.data));
dataToSend = response.data;
dataToSend.deviceInfo = deviceInfo;
dataToSend.imageUrl = base64_encode(url);
// dataToSend.imageUrl = "Yo";
sendIOTMessage(dataToSend);
})
.catch(function (error) {
console.log(error);
});
}
/**
* Function to encode image to base 64
* @param file file to encode
* @returns base64 string of image
*/
function base64_encode(file) {
// read binary data
var bitmap = fs.readFileSync(file);
// convert binary data to base64 encoded string
return new Buffer(bitmap).toString('base64');
}
/**
* Function to send message through Azure IOT Hub
* @param data
*/
function sendIOTMessage(data) {
// Simulate telemetry.
const message = new Message(JSON.stringify(data));
// Send the message.
client.sendEvent(message, function (err) {
if (err) {
console.error('send error: ' + err.toString());
} else {
console.log("message sent");
}
// call take photo again
// takePhoto();
});
}
/**
* Function to take a photo from webcam
*/
function takePhoto() {
// Call Azure image recognition
Webcam.capture("webcam", function( err, data ) {
analyze('./webcam.jpg');
});
}
/**
* Function called on startup
*/
function init() {
console.log(deviceInfo);
const socket = socketIOClient(ENDPOINT);
socket.on('connect', function (socket) {
console.log('connected to server!');
});
socket.on("pairRequest", data => {
if(data.deviceId === deviceInfo.id) {
deviceInfo.status = "paired";
deviceInfo.owner = data.owner;
deviceInfo.name = "Fruit Monitor";
fs.writeFile('device.json', JSON.stringify(deviceInfo), 'utf8', ()=>{
console.log("device paired!")
deviceInfo = require('./device.json');
socket.emit("devicePaired", deviceInfo);
});
}
});
// implementation to take photo every x seconds
setInterval(function(){
if(deviceInfo.status !== "paired") {
console.log("needs to be paired...")
}
else {
takePhoto();
}
}, 5000);
}