Created
January 6, 2021 13:20
-
-
Save nicolas-zozol/1f06ec0822c32b5e4ce30ffaba09947a to your computer and use it in GitHub Desktop.
Sonoff basic javascript code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require('dotenv').config() | |
const ewelink = require('ewelink-api') | |
const credentials = { | |
username: process.env.EMAIL, | |
password: process.env.PASSWORD | |
} | |
const devices = { | |
lili: process.env.LILI // device Id | |
} | |
const connection = new ewelink({ | |
email: process.env.EMAIL, | |
password: process.env.PASSWORD, | |
region: process.env.REGION // eu, us .... | |
}) | |
connection.getDevices().then(work) // connection.getDevices().then(console.log) to find device ids | |
async function work() { | |
try { | |
const {temperature, power} = await liliStatus() | |
console.log({temperature, power}); | |
if (temperature < 18 && !power && timeAndDayToPowerOn()) { | |
console.log({temperature, power}, "Should power lili on"); | |
await connection.setDevicePowerState(devices.lili, 'on') | |
}else{ | |
if(power){ | |
await connection.setDevicePowerState(devices.lili, 'off') | |
} // else already powered off | |
} | |
} catch (e) { | |
console.error(e) | |
} | |
} | |
function timeAndDayToPowerOn(){ | |
// look into google calendar | |
return true; | |
} | |
// fetch device informations and parse them | |
async function liliStatus() { | |
const stringTemperature = (await connection.getDeviceCurrentTemperature(devices.lili)).temperature | |
const stringPower = (await connection.getDevicePowerState(devices.lili)).state | |
const temperature = parseFloat(stringTemperature) | |
const power = stringPower ==='on'; | |
return {temperature, power} | |
} | |
async function powerLili() { | |
await connection.setDevicePowerState(devices.lili, 'on') | |
console.log("Lili powered on"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
.env
file is placed at the same level thanpackage.json