Files
sprocket-core/tools/ota.js
Patrick Balsiger dbb4ce9de7 Resolve "OTA"
2018-08-03 11:01:42 +00:00

116 lines
2.5 KiB
JavaScript

// Mesh msg type = 7
// OTA paket types: START = 0, DATA = 1, END = 3
const fs = require('fs');
const crypto = require('crypto');
const mqtt = require('mqtt');
let filePath = '../.pioenvs/mesh/firmware.bin';
let broker = 'mqtt://192.168.1.2:1883';
const readFile = filePath => new Promise((resolve, reject) => {
fs.readFile(filePath, (err, data) => {
if (err) reject(err);
else resolve(data);
});
});
const checksumFile = (hashName, path) => new Promise((resolve, reject) => {
let hash = crypto.createHash(hashName);
let stream = fs.createReadStream(path);
stream.on('error', err => reject(err));
stream.on('data', chunk => hash.update(chunk));
stream.on('end', () => resolve(hash.digest('hex')));
});
const upload = async path => {
let content = await readFile(path);
let md5 = await checksumFile('MD5', path);
let b64Content = content.toString('base64');
console.log(`MD5 Hash: ${md5}`);
//console.log(b64Content);
//mqttClient(md5, b64Content);
};
const initializeUpdateMessage = (fromNode, toNode, md5Hash) => {
return {
dest: toNode,
from: fromNode,
type: 7,
msg: {
type: 0,
md5: md5Hash
}
};
};
const firmwareUpdateMessage = (fromNode, toNode, firmware) => {
return {
dest: toNode,
from: fromNode,
type: 7,
msg: {
type: 1,
data: firmware,
length: firmware.length
}
};
};
const mqttClient = (md5, data) => {
var client = mqtt.connect(broker);
let target = 3895627464;
// button thingy=> dest: "757307466",
let initMsg = {
dest: target,
from: 1,
type: 7,
msg: {
type: 0,
md5: md5
}
};
let dataMsg = {
dest: target,
from: 1,
type: 7,
msg: {
type: 1,
data: data,
length: data.length
}
};
let sm = {
OTA_INIT: {
FAILED: console.log,
DONE: OTA_DATA.WRITE
},
OTA_DATA: {
WRITE: console.log,
DONE: OTA_FIN.RESTART,
FAILED: console.log
},
OTA_FIN: {
RESTART: console.log
}
};
client.on('connect', function () {
client.subscribe('/up/wirelos/gateway');
client.publish('/down/wirelos', JSON.stringify(initMsg));
})
client.on('message', function (topic, message) {
// message is Buffer
console.log(message.toString());
let obj = JSON.parse(message.toString());
sm[obj.type][obj.state](obj);
//if(JSON.parse(message.toString()).type == 'OTA_INIT'){
// client.publish('/down/wirelos', JSON.stringify(dataMsg));
//}
client.end();
})
return client;
};
upload(filePath);