-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
65 lines (54 loc) · 2.03 KB
/
main.js
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
#!/usr/bin/env node
import { connect } from 'mqtt';
import config from './src/config.js';
import { DeviceCache } from './src/devices-cache.js';
import { remoteExecute } from './src/remote.js';
import { existsSync } from 'fs';
import path from "path";
const LOCALCONFIG = "config.local.js"
const importUrl = new URL(import.meta.url)
importUrl.pathname = path.join(importUrl.pathname, "..", LOCALCONFIG)
const localConfigUrl = importUrl.href
// Apply local config if it exists
// To create a local config, copy src/config.js as template, tename it to config.local.js and remove what you don't need and define what you
try {
let localConfig = await import(localConfigUrl)
Object.assign(config, localConfig?.default)
console.log("Using config: ",config,"\n\n");
} catch(e) {
console.log("No local config found ", localConfigUrl);
}
let deviceCache = new DeviceCache(config.devices, config)
const client = connect(config.mqttConnectString);
function ensureConnected() {
if (!client.connected) client.on("connect", () => {
client.subscribe(config.mqttConnectTopic, (err) => {
if (!err) {
console.log("Successfully connected to MQTT")
}
});
});
}
ensureConnected()
setInterval(ensureConnected, config.checkConnectionIntervalMs)
client.on('close', function() {
console.log('Client disconnected');
});
client.on("message", (topic, message) => {
if (topic == config.mqttConnectTopic) {
let rc = message.toString()
let matchingRemotes = config.remotes.filter(r => Array.isArray(r.rc)?r.rc.includes(rc):r.rc == rc)
if (matchingRemotes.length > 0) {
matchingRemotes.forEach(remote => {
if (!remote.lastCommandDate || ((Date.now() - remote.lastCommandDate) > config.delayBetweenCommandsMs)) {
remote.lastCommandDate = Date.now()
remoteExecute(remote, deviceCache)
} else {
console.warn(`Remote ${rc} command already sent in the last ${config.delayBetweenCommandsMs}ms`)
}
})
} else {
console.error(`Remote ${rc} not found in config`)
}
}
});