-
Notifications
You must be signed in to change notification settings - Fork 8
/
z-way.coffee
567 lines (470 loc) · 17.6 KB
/
z-way.coffee
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
module.exports = (env) ->
# ###require modules included in pimatic
# To require modules that are included in pimatic use `env.require`. For available packages take
# a look at the dependencies section in pimatics package.json
Promise = env.require 'bluebird'
assert = env.require 'cassert'
rp = env.require 'request-promise'
class ZWayPlugin extends env.plugins.Plugin
# ####init()
# The `init` function is called by the framework to ask your plugin to initialise.
#
# #####params:
# * `app` is the [express] instance the framework is using.
# * `framework` the framework itself
# * `config` the properties the user specified as config for your plugin in the `plugins`
# section of the config.json file
#
#
init: (app, @framework, @config) =>
env.logger.info("initialized pimatic-z-way with hostname " + @config.hostname)
deviceConfigDef = require("./device-config-schema")
@options =
'json': true
'simple': true
'resolveWithFullResponse': false
'jar': true
@authenticated = false
env.logger.debug "registering devices"
@framework.deviceManager.registerDeviceClass("ZWaySwitch", {
configDef: deviceConfigDef.ZWaySwitch,
createCallback: (config) => new ZWaySwitch(config)
})
@framework.deviceManager.registerDeviceClass("ZWayDimmer", {
configDef: deviceConfigDef.ZWayDimmer,
createCallback: (config) => new ZWayDimmer(config)
})
@framework.deviceManager.registerDeviceClass("ZWayThermostat", {
configDef: deviceConfigDef.ZWayThermostat,
createCallback: (config, lastState) => new ZWayThermostat(config, lastState)
})
@framework.deviceManager.registerDeviceClass("ZWayPowerSensor", {
configDef: deviceConfigDef.ZWayPowerSensor,
createCallback: (config) => new ZWayPowerSensor(config)
})
@framework.deviceManager.registerDeviceClass("ZWayLuminescenceSensor", {
configDef: deviceConfigDef.ZWayLuminescenceSensor,
createCallback: (config) => new ZWayLuminescenceSensor(config)
})
@framework.deviceManager.registerDeviceClass("ZWayHumiditySensor", {
configDef: deviceConfigDef.ZWayHumiditySensor,
createCallback: (config) => new ZWayHumiditySensor(config)
})
@framework.deviceManager.registerDeviceClass("ZWayDoorWindowSensor", {
configDef: deviceConfigDef.ZWayDoorWindowSensor,
createCallback: (config) => new ZWayDoorWindowSensor(config)
})
@framework.deviceManager.registerDeviceClass("ZWayTemperatureSensor", {
configDef: deviceConfigDef.ZWayTemperatureSensor,
createCallback: (config) => new ZWayTemperatureSensor(config)
})
@framework.deviceManager.registerDeviceClass("ZWayMotionSensor", {
configDef: deviceConfigDef.ZWayMotionSensor,
createCallback: (config) => new ZWayMotionSensor(config)
})
@framework.deviceManager.registerDeviceClass("ZWayShutterController", {
configDef: deviceConfigDef.ZWayShutterController,
createCallback: (config) => new ZWayShutterController(config)
})
sendCommand: (virtualDeviceId, command) ->
address = "http://" + @config.hostname + ":8083/ZAutomation/api/v1/devices/" + virtualDeviceId + "/command/" + command
env.logger.debug("sending command " + address)
@logIn()
.then ()=>
commandAnswer = rp address, @options
.then (json) =>
try
# needed because json could contain circular reference
env.logger.debug "received command answer:#{JSON.stringify(json)}"
catch e
env.logger.debug "received command answer"
return json
return commandAnswer
.catch (error)=>
if error.message.match(401)
env.logger.error ("reseting authentication")
@authenticated = false
getDeviceDetails: (virtualDeviceId) ->
address = "http://" + @config.hostname + ":8083/ZAutomation/api/v1/devices/" + virtualDeviceId
@logIn()
.then ()=>
deviceDetails = rp address, @options
.then (json) =>
try
# needed because json could contain circular reference
env.logger.debug "received device details:#{JSON.stringify(json)}"
catch e
env.logger.debug "received device details"
return json
return deviceDetails
.catch (error)=>
if error.message.match(401)
env.logger.error ("resetting authentication")
@authenticated = false
logIn: ()->
if @authenticated then return Promise.resolve()
address = "http://" + @config.hostname + ":8083/ZAutomation/api/v1/login"
env.logger.debug("logging in " + address)
authOptions = JSON.parse(JSON.stringify(@options));
authOptions.body =
'login': @config.username
'password': @config.password
authOptions.method = 'POST'
loginRequest = rp address, authOptions
.then (json) =>
env.logger.debug "login success: #{json}"
@authenticated = true
return json
.catch (error) =>
env.logger.debug "error logging in: #{error}"
return loginRequest
sleep: (ms) ->
start = new Date().getTime()
continue while new Date().getTime() - start < ms
logError: (msg, sensorTitle, deviceId) ->
env.logger.error("#{deviceId} (#{sensorTitle}):", msg)
class ZWaySwitch extends env.devices.PowerSwitch
constructor: (@config) ->
@id = @config.id
@name = @config.name
@virtualDeviceId = @config.virtualDeviceId
updateValue = =>
if @config.interval > 0
@getState().finally( =>
@_updateInterval = setTimeout(updateValue, @config.interval * 1000)
)
super()
updateValue()
changeStateTo: (state) ->
if @state is state then return Promise.resolve()
command = if state then "on" else "off"
return plugin.sendCommand(@virtualDeviceId, command).then( =>
@_setState(state)
# wait before the switch status is read
plugin.sleep 1500
@getState()
).catch( (e) =>
plugin.logError("state change failed with #{e.message}", @name, @id)
)
getState: () ->
return plugin.getDeviceDetails(@virtualDeviceId).then( (json) =>
state = json.data.metrics.level
@_setState(state == "on")
return @_state
).catch( (e) =>
plugin.logError("state update failed with #{e.message}", @name, @id)
return @_state
)
destroy: ->
clearTimeout(@_updateInterval)
super()
class ZWayDimmer extends env.devices.DimmerActuator
constructor: (@config) ->
@id = @config.id
@name = @config.name
@virtualDeviceId = @config.virtualDeviceId
updateValue = =>
if @config.interval > 0
@getDimlevel().finally( =>
@_updateInterval = setTimeout(updateValue, @config.interval * 1000)
)
super()
updateValue()
changeDimlevelTo: (level) ->
if @_dimlevel is level then return Promise.resolve()
return plugin.sendCommand(@virtualDeviceId, "exact?level=#{level}").then( =>
@_setDimlevel(level)
).catch( (e) =>
plugin.logError("dim level change failed with #{e.message}", @name, @id)
)
getDimlevel: () ->
return plugin.getDeviceDetails(@virtualDeviceId).then( (json) =>
level = json.data.metrics.level
@_setDimlevel(level)
return @_dimlevel
).catch( (e) =>
plugin.logError("dim level update failed with #{e.message}", @name, @id)
return @_dimlevel
)
destroy: ->
clearTimeout(@_updateInterval)
super()
class ZWayThermostat extends env.devices.HeatingThermostat
constructor: (@config, lastState) ->
@id = @config.id
@name = @config.name
@virtualDeviceId = @config.virtualDeviceId
@_temperatureSetpoint = lastState?.temperatureSetpoint?.value
@_mode = lastState?.mode?.value or "auto"
@_battery = lastState?.battery?.value or "ok"
@_synced = true
updateValue = =>
if @config.interval > 0
@getTemperatureSetpoint().finally( =>
@_updateInterval = setTimeout(updateValue, @config.interval * 1000)
)
super()
updateValue()
changeTemperatureTo: (setpoint) ->
if @_temperatureSetpoint is setpoint then return Promise.resolve()
return plugin.sendCommand(@virtualDeviceId, "exact?level=#{setpoint}").then( =>
@_setSetpoint(setpoint)
).catch( (e) =>
plugin.logError("temperature setpoint change failed with #{e.message}", @name, @id)
)
getTemperatureSetpoint: () ->
return plugin.getDeviceDetails(@virtualDeviceId).then( (json) =>
level = json.data.metrics.level
@_setSetpoint(level)
return @_temperatureSetpoint
).catch( (e) =>
plugin.logError("temperature setpoint update failed with #{e.message}", @name, @id)
return @_temperatureSetpoint
)
changeModeTo: (mode) ->
plugin.logError("setting mode not yet supported", @name, @id)
return Promise.resolve()
destroy: ->
clearTimeout(@_updateInterval)
super()
class ZWayPowerSensor extends env.devices.Sensor
constructor: (@config) ->
@id = @config.id
@name = @config.name
@virtualDeviceId = @config.virtualDeviceId
@attributes = {}
sensor = "power"
@attributes[sensor] = {}
@attributes[sensor].description = "Current Power Consumption"
@attributes[sensor].type = "number"
getter = ( =>
return plugin.getDeviceDetails(@virtualDeviceId).then( (json) =>
val = json.data.metrics.level
unit = json.data.metrics.scaleTitle
@attributes[sensor].unit = unit
return val
)
)
@_createGetter(sensor, getter)
@_updateInterval = setInterval( ( =>
getter().then( (value) =>
@emit sensor, value
).catch( (error) =>
plugin.logError("updating sensor value failed with #{error.message}", @name, @id)
)
), @config.interval * 1000)
super()
destroy: ->
clearTimeout(@_updateInterval)
super()
class ZWayDoorWindowSensor extends env.devices.ContactSensor
constructor: (@config, lastState) ->
@id = @config.id
@name = @config.name
@virtualDeviceId = @config.virtualDeviceId
@_contact = lastState?.contact?.value or false
@readContactValue()
@_updateInterval = setInterval( ( => @readContactValue().catch( (error) =>
plugin.logError("updating sensor value failed with #{error.message}", @name, @id)
)
), @config.interval * 1000)
super()
setContactValue: (value) ->
assert value is 1 or value is 0
state = (if value is 1 then true else false)
if @config.inverted then state = not state
@_setContact state
readContactValue: ->
return plugin.getDeviceDetails(@virtualDeviceId).then( (json) =>
val = json.data.metrics.level
value = 0
if val is "on" then value = 1
@setContactValue value
return @_contact
)
getContact: () -> if @_contact? then Promise.resolve(@_contact) else @readContactValue()
destroy: ->
clearTimeout(@_updateInterval)
super()
class ZWayTemperatureSensor extends env.devices.TemperatureSensor
temperature: null
constructor: (@config) ->
@id = @config.id
@name = @config.name
@virtualDeviceId = @config.virtualDeviceId
sensor = "temperature"
getter = ( =>
return plugin.getDeviceDetails(@virtualDeviceId).then( (json) =>
val = json.data.metrics.level
unit = json.data.metrics.scaleTitle
@attributes[sensor].unit = unit
return val
)
)
@_createGetter(sensor, getter)
@_updateInterval = setInterval( ( =>
getter().then( (value) =>
@emit sensor, value
).catch( (error) =>
plugin.logError("updating sensor value failed with #{error.message}", @name, @id)
)
), @config.interval * 1000)
super()
destroy: ->
clearTimeout(@_updateInterval)
super()
class ZWayLuminescenceSensor extends env.devices.Sensor
constructor: (@config) ->
@id = @config.id
@name = @config.name
@virtualDeviceId = @config.virtualDeviceId
@attributes = {}
sensor = "luminescence"
@attributes[sensor] = {}
@attributes[sensor].description = "Current Luminescence"
@attributes[sensor].type = "number"
getter = ( =>
return plugin.getDeviceDetails(@virtualDeviceId).then( (json) =>
val = json.data.metrics.level
unit = json.data.metrics.scaleTitle
@attributes[sensor].unit = unit
return val
)
)
@_createGetter(sensor, getter)
@_updateInterval = setInterval( ( =>
getter().then( (value) =>
@emit sensor, value
).catch( (error) =>
plugin.logError("updating sensor value failed with #{error.message}", @name, @id)
)
), @config.interval * 1000)
super()
destroy: ->
clearTimeout(@_updateInterval)
super()
class ZWayHumiditySensor extends env.devices.Sensor
constructor: (@config) ->
@id = @config.id
@name = @config.name
@virtualDeviceId = @config.virtualDeviceId
@attributes = {}
sensor = "humidity"
@attributes[sensor] = {}
@attributes[sensor].description = "Current Humidity"
@attributes[sensor].type = "number"
getter = ( =>
return plugin.getDeviceDetails(@virtualDeviceId).then( (json) =>
val = json.data.metrics.level
unit = json.data.metrics.scaleTitle
@attributes[sensor].unit = unit
return val
)
)
@_createGetter(sensor, getter)
@_updateInterval = setInterval( ( =>
getter().then( (value) =>
@emit sensor, value
).catch( (error) =>
plugin.logError("updating sensor value failed with #{error.message}", @name, @id)
)
), @config.interval * 1000)
super()
destroy: ->
clearTimeout(@_updateInterval)
super()
class ZWayMotionSensor extends env.devices.PresenceSensor
constructor: (@config, lastState) ->
@id = @config.id
@name = @config.name
@virtualDeviceId = @config.virtualDeviceId
@_presence = lastState?.presence?.value or false
@readPresenceValue()
@_updateInterval = setInterval( ( => @readPresenceValue().catch( (error) =>
plugin.logError("updating sensor value failed with #{error.message}", @name, @id)
)
), @config.interval * 1000)
super()
setPresenceValue: (value) ->
assert value is 1 or value is 0
state = (if value is 1 then true else false)
if @config.inverted then state = not state
@_setPresence state
readPresenceValue: ->
return plugin.getDeviceDetails(@virtualDeviceId).then( (json) =>
val = json.data.metrics.level
value = 0
if val is "on" then value = 1
@setPresenceValue value
return @_presence
)
destroy: ->
clearTimeout(@_updateInterval)
super()
class ZWayShutterController extends env.devices.ShutterController
constructor: (@config, lastState) ->
@id = @config.id
@name = @config.name
@_position = lastState?.position?.value or 'stopped'
@virtualDeviceId = @config.virtualDeviceId
updateValue = =>
if @config.interval > 0
@getPosition().finally( =>
@_updateInterval = setTimeout(updateValue, @config.interval * 1000)
)
super()
updateValue()
stop: ->
if @_position is 'stopped' then return Promise.resolve()
return plugin.sendCommand(@virtualDeviceId, 'stop').then( =>
@_lastSendTime = new Date().getTime()
@_setPosition('stopped')
@emit "position", @_position
).catch( (e) =>
plugin.logError("stop failed with #{e.message}", @name, @id)
)
moveUp: ->
if @_position is 'up' then return Promise.resolve()
return plugin.sendCommand(@virtualDeviceId, 'exact?level=99').then( =>
@_lastSendTime = new Date().getTime()
@_setPosition('up')
@emit "position", @_position
).catch( (e) =>
plugin.logError("move up failed with #{e.message}", @name, @id)
)
moveDown: ->
if @_position is 'down' then return Promise.resolve()
return plugin.sendCommand(@virtualDeviceId, 'exact?level=0').then( =>
@_lastSendTime = new Date().getTime()
@_setPosition('down')
@emit "position", @_position
).catch( (e) =>
plugin.logError("move down failed with #{e.message}", @name, @id)
)
moveToPosition: (position) ->
if position is @_position then return Promise.resolve()
if position is 'stopped' then return @stop()
else
if position is 'up' then return @moveUp()
else
if position is 'down' then return @moveDown()
getPosition: () ->
return plugin.getDeviceDetails(@virtualDeviceId).then( (json) =>
level = json.data.metrics.level
if level is 0 then positionTemp = 'down'
else
if level is 99 then positionTemp = 'up'
else
positionTemp = 'stopped'
@_setPosition(positionTemp)
@emit "position", @_position
return @_position
).catch( (e) =>
plugin.logError("position update failed with #{e.message}", @name, @id)
return @_dimlevel
)
destroy: ->
clearTimeout(@_updateInterval)
super()
plugin = new ZWayPlugin
return plugin