mirror of
https://github.com/skydiver/ewelink-api.git
synced 2025-12-21 21:33:11 +01:00
* set APP_ID and APP_SECRET from main class * add APP_ID and APP_SECRET as class constructor parameters * updated test case * updated test case * added new test case * docs updated * Release v3.1.0 - "setWSDevicePowerState" (#96) * new mixing to control devices using websocket * switch status on single channel devices * working on deviceControl mixin * better error handling * working on fix for shared devices * refactor/cleanup * added helper function * added docs for new method * return device new status * added test cases * properly close websocket connection and clean used properties * added test cases * error detection enhancements * added test cases * error detection enhancements * added new test file to jest setup * method renamed * fix for closing websocket connection * new getWSDevicePowerState method * added test cases * re-arrange tests * added new test cases * extract helpers methods * added test case * close WebSocket connection on auth error * updated docs * updated dependencies * fix for "forbidden" error * updated dependencies
45 lines
1.1 KiB
JavaScript
45 lines
1.1 KiB
JavaScript
const W3CWebSocket = require('websocket').w3cwebsocket;
|
|
const WebSocketAsPromised = require('websocket-as-promised');
|
|
|
|
const wssLoginPayload = require('../payloads/wssLoginPayload');
|
|
|
|
module.exports = {
|
|
/**
|
|
* Open a socket connection to eWeLink
|
|
* and execute callback function with server message as argument
|
|
*
|
|
* @param callback
|
|
* @param heartbeat
|
|
* @returns {Promise<WebSocketAsPromised>}
|
|
*/
|
|
async openWebSocket(callback, ...{ heartbeat = 120000 }) {
|
|
const payloadLogin = wssLoginPayload({
|
|
at: this.at,
|
|
apiKey: this.apiKey,
|
|
appid: this.APP_ID,
|
|
});
|
|
|
|
const wsp = new WebSocketAsPromised(this.getApiWebSocket(), {
|
|
createWebSocket: wss => new W3CWebSocket(wss),
|
|
});
|
|
|
|
wsp.onMessage.addListener(message => {
|
|
try {
|
|
const data = JSON.parse(message);
|
|
callback(data);
|
|
} catch (error) {
|
|
callback(message);
|
|
}
|
|
});
|
|
|
|
await wsp.open();
|
|
await wsp.send(payloadLogin);
|
|
|
|
setInterval(async () => {
|
|
await wsp.send('ping');
|
|
}, heartbeat);
|
|
|
|
return wsp;
|
|
},
|
|
};
|