64 lines
2.2 KiB
JavaScript
64 lines
2.2 KiB
JavaScript
import to from 'await-to-js'
|
|
// import Hass from '../src/homeassistant'
|
|
import Hass from 'ha'
|
|
import moment from 'moment'
|
|
|
|
let opts = {
|
|
pingpong:false,
|
|
// url: 'ws://10.0.0.3:8123',
|
|
host: 'nas.kebler.net',
|
|
access_token: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiI5M2Q0YjdjNDg2MTc0MzY4YWE2MTE5NTU5ZDdkYjhjYyIsImlhdCI6MTU2NDMyNTkwNCwiZXhwIjoxODc5Njg1OTA0fQ.UBQkyqS88YbtcO90t1bSom3uYZy-C4vhgkKFCIzqbNU'
|
|
}
|
|
|
|
let hass = new Hass(opts)
|
|
|
|
;
|
|
(async () => {
|
|
hass.on('connection', msg => console.log(`connection: ${msg}`))
|
|
await hass.connect()
|
|
if (hass.eventBusId) console.log('listener established for HA event bus')
|
|
|
|
hass.on('error', err => console.log(err))
|
|
|
|
// hass.on('event', handleAllEvents)
|
|
// function handleAllEvents (ev) {
|
|
// console.log ('All HA event\n',ev)
|
|
// }
|
|
|
|
// hass.stateChange('input_select.test_schedule_repeatin', handleInput)
|
|
// function handleInput (ev) {
|
|
// console.log ('test schedule repeat in state', ev)
|
|
// }
|
|
let name = 'schedule'
|
|
let list = ['sensor.test_schedule_delta','input_number.test_schedule_base_hour','input_number.test_schedule_base_minute']
|
|
await hass.makeWatchList(list,name)
|
|
hass.on('wl-'+name,(ent) => {
|
|
scheduleComputeNext(ent.entity_id)
|
|
})
|
|
|
|
async function scheduleComputeNext(ent) {
|
|
console.log(`${ent} changed updating computed next time`)
|
|
let vars = hass.getWatchList(name,true)
|
|
console.log('updated scheuler inputs for processing\n',vars)
|
|
let baseTS = vars[list[2]].state*60+vars[list[1]].state*3600
|
|
let dt = new Date()
|
|
let intoDayTS = (dt.getSeconds() + (60 * dt.getMinutes()) + (60 * 60 * dt.getHours()))
|
|
let nowTS = Math.floor(Date.now()/1000)
|
|
let nextTS = nowTS - intoDayTS + baseTS
|
|
console.log(baseTS,intoDayTS,nowTS, nowTS-intoDayTS,nextTS)
|
|
while (nowTS > nextTS) {
|
|
console.log(`now ${nowTS} beyond next ${nextTS} adding delta ${vars[list[0]].state} hours`)
|
|
nextTS += vars[list[0]].state*3600
|
|
}
|
|
console.log(nextTS)
|
|
let nextDateTime = moment(nextTS*1000).format('ddd, MMM Do h:mm A')
|
|
console.log(await hass.setVariable('test_schedule_next', nextDateTime))
|
|
}
|
|
|
|
|
|
|
|
})().catch(err => {
|
|
console.error('FATAL: UNABLE TO START SYSTEM!\n',err)
|
|
process.kill(process.pid, 'SIGTERM')
|
|
})
|