aboutsummaryrefslogtreecommitdiff
path: root/src/lib/helpers/action.ts
blob: 87364ba6afa5088836f881e169b6671c4f22a4cc (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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
//
// ~~~ 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 actions
function _runActions(actions) {

    actions.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)

    })
}

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

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

    _runActions(action.do)
}

// run on motion
export function onMotion(action, payload) {

    if (payload.presence === true) {

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

        if (!global.activeActions.includes(action.id)) {
            global.activeActions.push(action.id)
        }

        if (global.activeUndos.includes(action.id)) {
            global.activeUndos = global.activeUndos.filter((trigger) => trigger !== action.id)
        }

        _runActions(action.do)

    } else {

        if (global.activeActions.includes(action.id)) {

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

            const inverseActions = action.do.map((inverseAction) => {
                let actionDo

                switch (inverseAction.action) {
                    case "on":
                        actionDo = "off"
                        break

                    case "off":
                        actionDo = "on"
                        break

                    default:
                        actionDo = inverseAction.action
                }

                return {
                    ...inverseAction,
                    action: actionDo
                }
            })

            global.activeActions = global.activeActions.filter((trigger) => trigger !== action.id)

            _runActions(inverseActions)
        }
    }
}

// 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
    })
}