UNPKG

anniot-core

Version:
83 lines (80 loc) 2.83 kB
var i = require("socket.io-client"); const Gpio = require("onoff").Gpio; /** * AnnIoT core configure client details * @param {Object} config - Device configration * @param {string} config.mail - Mail address that device integrated to it * @param {string} config.id - Device id that you want to connect it */ exports.core = function ({ mail, id }) { if (mail == undefined || id == undefined) { //Catch user configuration var err = new Error("Wrong connection details provided"); err.code = "wrongConnectionDetails"; throw err; } /** * Connect to server * @param {boolean} autoConnect - Auto connect to server in case of connection failure **/ this.connect = function (autoConnect) { class coreEmitter extends require('events') {} const emitter = new coreEmitter(); var client = i.connect('https://api.projectann.xyz', { path: "/iotCloud", transportOptions: { polling: { extraHeaders: { server: "AnnIoT", loginObject: JSON.stringify({ type: "device", ver : "1.1.9.18", info: { mail: mail, deviceId: id, deviceSerial: "none", //none for now } }) } } } }) .once('connect', function () { emitter.emit("connect", true); client.once("connectionSuccess", function (device) { emitter.emit("verify", device); client.on(device.info.deviceID + "-request_functionEvents", function (data) { if (data.payload.type == "digitalRead") { new Gpio(Number(data.payload.port), 'in').read().then(val => { client.emit("response_functionRead",{ type: data.payload.type, //readDigital,sensors [Humidty-vb] componentId: data.payload.id, element: data.payload.element, payload: { status: val == 1 ? true : false } }); }); }; }); client.on(device.info.deviceID + "-write_functionEvents", function (data) { if (data.payload.type == "switch") { new Gpio(Number(data.payload.port), "out").writeSync(data.payload.status == true ? 1 : 0); }; }); }); emitter.on("requestDisconnect", function () { client.disconnect(true); }); emitter.on("requestConnect", function () { client.connect(); }); client.on("errMessage", function (data) { emitter.emit("error", data); }); }); return emitter; } }