aboutsummaryrefslogtreecommitdiff
path: root/src/lib/helpers/action.ts
blob: 59677eac70feaf8c42e062bed70a64f67de2112c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
//
// ~~~ action helper utilities
//

// imports
import { sendMessage } from "@lib/mqtt.ts"
import allActions from "@lib/config/actions.ts"
import allDevices from "@lib/config/devices.ts"

// run on button press
export function onPress(action) {

    console.debug(`-> running ${action.id}`)

    const actionDo = action.do

    actionDo.forEach((action) => {

        const device = allDevices.find((device) => device.id === action.device)

        // todo: error handling

        const topic = `${device.mqtt}/set`
        const message = JSON.stringify({ state: action.action.toUpperCase() })

        console.debug(`    -> send state ${action.action} to ${action.device}`)
        sendMessage(topic, message)

    })
}

// validate actions config
export function validate() {

    if (allActions.length < 1) return true

    return allActions.every((action) => {

        const onDevice = allDevices.find((device) => device.id === action.on.device)
        if (!onDevice) return false

        // todo: rest of the props

        return true
    })
}