Skip to content

Instantly share code, notes, and snippets.

@beveradb
Forked from robertklep/sonoff-lan-mode-test.js
Last active September 15, 2022 11:09
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save beveradb/0def87f98205bd6647a574eea609b146 to your computer and use it in GitHub Desktop.
Save beveradb/0def87f98205bd6647a574eea609b146 to your computer and use it in GitHub Desktop.
const WebSocket = require('ws');
// Turns out you don't need to dump packets at all - you don't even need a valid API key or device ID when it's in LAN mode.
// All you need to know is the IP address of the device, as it happily accepts WebSocket messages with any string as the "apikey".
const IPADDRESS = '192.168.0.72';
const seq = () => String(Date.now());
const ws = new WebSocket('ws://' + IPADDRESS + ':8081', [ 'chat' ]);
const nonce = 'nonce';
// Log all messages received from the device
ws.on('message', function incoming(json) {
const messageData = JSON.parse(json);
console.log('Received Message: %j', messageData);
});
// Define method to send update message to change switch state
function updateState(newState) {
const updateMessageJSON = JSON.stringify({
"action": "update",
"deviceid": nonce,
"apikey": nonce,
"selfApikey": nonce,
"params": {
"switch": newState
},
"sequence": seq(),
"userAgent": "app"
});
console.log('Sending Update Message: %s', updateMessageJSON);
ws.send(updateMessageJSON);
}
// Initiate session with device in LAN mode by sending "userOnline" action message
ws.on('open', function initiateSession(ev) {
const initiateSessionMessageJSON = JSON.stringify({
"action": "userOnline",
"ts": String(0 | Date.now / 1000),
"version": 6,
"apikey": nonce,
"sequence": seq(),
"userAgent": "app"
});
console.log('Sending User Online Message: %s', initiateSessionMessageJSON);
ws.send(initiateSessionMessageJSON);
});
function switchOn() {
console.log('Switching On');
updateState('on');
}
function switchOff() {
console.log('Switching Off');
updateState('off');
}
function switchOnFor5Seconds() {
switchOn();
setTimeout(switchOff, 5000);
}
setInterval(switchOnFor5Seconds, 10000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment