-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
192 lines (168 loc) · 4.73 KB
/
index.ts
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
import { Gpio } from 'onoff';
import * as SunCalc from 'suncalc';
import { clearTimeout } from 'timers';
import * as TuyaDevice from 'tuyapi';
import * as winston from 'winston';
type Binary = 0 | 1;
function invert(value: Binary) {
return value ? 0 : 1;
}
const LATITUDE = 51.5; // London latitude
const LONGITUDE = -0.1; // London longitude
const TUYA_ID = process.env.TUYA_ID;
const TUYA_KEY = process.env.TUYA_KEY;
const IP = process.env.IP;
if (!TUYA_ID || !TUYA_KEY) {
throw new Error('You need to provide Tuya auth info!');
}
const TIMER_DURATION_S = parseInt(process.env.TIMER_DURATION || '300', 10);
const TIMER_DURATION_MS = TIMER_DURATION_S * 1000;
const TIMER_ACTIVATION_DELAY_S = parseInt(
process.env.TIMER_ACTIVATION_DELAY || '5',
10,
);
const TIMER_ACTIVATION_DELAY_MS = TIMER_ACTIVATION_DELAY_S * 1000;
const envPins = [
['DOOR_PIN', process.env.DOOR_PIN || '17'],
['DOOR_LED_PIN', process.env.DOOR_LED_PIN || '27'],
['MOTION_PIN', process.env.MOTION_PIN || '23'],
['MOTION_LED_PIN', process.env.MOTION_LED_PIN || '22'],
['TIMER_LED_PIN', process.env.TIMER_LED_PIN || '18'],
];
const pins = envPins.map(([pinName, pin]) => {
const parsed = parseInt(pin, 10);
if (isNaN(parsed)) {
throw new Error(
`Error while parsing ${pinName} value: ${pin}. The value needs to be a proper GPIO number`,
);
}
return parsed;
});
const [
DOOR_PIN,
DOOR_LED_PIN,
MOTION_PIN,
MOTION_LED_PIN,
TIMER_LED_PIN,
] = pins;
interface IState {
door: Binary;
motion: Binary;
lastTimerCreation: Date;
motionTimer: NodeJS.Timer | null;
}
const state: IState = {
door: 0,
motion: 0,
lastTimerCreation: new Date(0),
motionTimer: null,
};
function isAfterSunset() {
const now = new Date();
const times = SunCalc.getTimes(now, LATITUDE, LONGITUDE);
return now >= times.sunsetStart || now <= times.sunriseEnd;
}
async function retry<T>(
actionName: string,
action: () => Promise<T>,
times: number,
) {
let retried;
for (retried = 0; retried < times; retried++) {
if (retried > 0) {
winston.warn(
`Action "${actionName}" failed! Retrying ${retried}th time...`,
);
}
try {
await action();
winston.info(`Action "${actionName}" succeeded!`);
return retried;
} catch {
// just advance
}
}
winston.error(`Action "${actionName}" failed`);
return null;
}
async function main() {
const gpios = [
new Gpio(DOOR_PIN, 'in', 'both'),
new Gpio(MOTION_PIN, 'in', 'both'),
new Gpio(DOOR_LED_PIN, 'out'),
new Gpio(MOTION_LED_PIN, 'out'),
new Gpio(TIMER_LED_PIN, 'out'),
];
const [door, motion, doorLed, motionLed, timerLed] = gpios;
const tuya = new TuyaDevice({
id: TUYA_ID,
key: TUYA_KEY,
ip: IP,
});
door.watch(async (err, value) => {
if (err) {
winston.error('Error while reading door pin:', err);
return;
}
state.door = invert(value);
winston.info(state.door ? 'Door opened!' : 'Door closed!');
doorLed.writeSync(state.door);
if (state.motionTimer) {
clearTimeout(state.motionTimer);
state.motionTimer = null;
timerLed.writeSync(0);
}
if (!state.door) {
timerLed.writeSync(1);
state.lastTimerCreation = new Date();
state.motionTimer = setTimeout(async () => {
state.motionTimer = null;
timerLed.writeSync(0);
winston.info('No presence detected');
if (isAfterSunset()) {
winston.info('Is after sunset so light likely on, turning light off');
await retry('Set false on Tuya', () => tuya.set({ set: false }), 3);
}
}, TIMER_DURATION_MS);
} else {
if (isAfterSunset()) {
winston.info('Is after sunset, turning light on');
try {
await retry('Set true on Tuya', () => tuya.set({ set: true }), 3);
} catch (e) {
winston.error('Connection error to Tuya occured');
}
}
}
});
motion.watch((err, value) => {
if (err) {
winston.error('Error while reading motion pin:', err);
return;
}
state.motion = value;
winston.info(state.motion ? 'Motion appeared!' : 'Motion disappeared!');
motionLed.writeSync(value);
if (state.motion && state.motionTimer) {
if (
new Date().getTime() - state.lastTimerCreation.getTime() <
TIMER_ACTIVATION_DELAY_MS
) {
winston.info('Motion probably due to door closing, disregarding');
return;
}
winston.info('Presence detected, keeping light on');
clearTimeout(state.motionTimer);
state.motionTimer = null;
timerLed.writeSync(0);
}
});
function unexport() {
for (const gpio of gpios) {
gpio.unexport();
}
}
process.on('SIGINT', unexport);
process.on('SIGTERM', unexport);
}
main();