-
Notifications
You must be signed in to change notification settings - Fork 3
/
mochad.coffee
375 lines (308 loc) · 13.3 KB
/
mochad.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
# Mochad plugin
module.exports = (env) ->
# Require lodash
_ = env.require 'lodash'
# Require the bluebird promise library
Promise = env.require 'bluebird'
# Require (internal lib) [matcher](https://github.com/pimatic/pimatic/blob/master/lib/matcher.coffee)
M = env.matcher
# Require [reconnect-net](https://www.npmjs.org/package/reconnect-net)
reconnect = require 'reconnect-net'
# ###Plugin class
class MochadPlugin extends env.plugins.Plugin
# ####init()
#
# #####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) =>
deviceConfigSchema = require("./mochad-device-schema")
@framework.deviceManager.registerDeviceClass("Mochad", {
configDef: deviceConfigSchema.Mochad,
createCallback: (config) => new Mochad(@framework, config)
})
@framework.on "after init", =>
# Check if the mobile-frontent was loaded and get a instance
mobileFrontend = @framework.pluginManager.getPlugin 'mobile-frontend'
if mobileFrontend?
mobileFrontend.registerAssetFile 'js', "pimatic-mochad/app/mochad-device.coffee"
mobileFrontend.registerAssetFile 'css', "pimatic-mochad/app/css/mochad-device.css"
mobileFrontend.registerAssetFile 'html', "pimatic-mochad/app/mochad-device.jade"
else
env.logger.warn "your plugin could not find the mobile-frontend. No gui will be available"
# #### Mochad class
class Mochad extends env.devices.Sensor
# ####constructor()
#
# #####params:
# * `deviceConfig`
#
constructor: (@framework, @config) ->
@id = @config.id
@name = @config.name
@host = @config.host
@port = @config.port
@units = @config.units
env.logger.debug("Initiating id='#{@id}', name='#{@name}', host='#{@host}', port='#{@port}'")
@unitsContainer = {}
for uconf in @units
switch uconf.class
when "MochadSwitch"
unit = new MochadSwitch(@, uconf)
when "MochadDimmer"
unit = new MochadDimmer(@, uconf)
if unit?
@unitsContainer[unit.housecode] ||= {}
if @unitsContainer[unit.housecode][unit.unitcode]
throw new Error "Unit #{unit.housecode}#{unit.unitcode} not unique in configuration"
@framework.deviceManager.registerDevice(unit)
@unitsContainer[unit.housecode][unit.unitcode] = unit;
@connection = null
@initConnection(@host, @port)
super()
# ####initConnection()
#
initConnection: (host, port)->
@lastSeen = {}
# TODO Test 1) Start with non-working connection, make connection work
# TODO Test 2) Start with working connection, make connection non-working and switch button in frontend
reconnector = reconnect(((conn) ->
# XXX Keep alive does not work [as expected](https://github.com/joyent/node/issues/6194)
conn.setKeepAlive(true, 0)
conn.setNoDelay(true)
conn.on 'data', ((data) ->
lines = data.toString()
# env.logger.debug(lines)
# Handling "st" result
# 06/04 21:50:55 Device status
# 06/04 21:50:55 House A: 1=1
# 06/04 21:50:55 House P: 1=1,2=0,3=1,4=0,5=1,6=0,7=0,8=0,9=0,10=0,11=0,12=0,13=0,14=0,15=0,16=0
# 06/04 21:50:55 Security sensor status
if m = /^\d{2}\/\d{2}\s+(?:\d{2}:){2}\d{2}\s+Device status\n((?:\d{2}\/\d{2}\s+(?:\d{2}:){2}\d{2}\s+House\s+[a-pA-P]:\s+(?:\d{1,2}=[01],?)+\n)*)/m.exec(lines)
for houseline in m[1].split("\n")
if n = /^\d{2}\/\d{2}\s+(?:\d{2}:){2}\d{2}\s+House\s+([a-pA-P]):\s+((?:\d{1,2}=[01],?)+)$/.exec(houseline)
housecode = n[1].toLowerCase()
for code2status in n[2].split(",")
o = code2status.split("=")
unitcode = parseInt(o[0], 10)
if @unitsContainer[housecode] and unit = @unitsContainer[housecode][unitcode]
state = if parseInt(o[1], 10) is 1 then true else false
env.logger.debug("House #{housecode} unit #{unitcode} has state #{state}");
unit._setState(state)
# Handling all-units-on/off
# example: 05/22 00:34:04 Rx PL House: P Func: All units on
# example: 05/22 00:34:04 Rx PL House: P Func: All units off
# example2: 00:04:29.391 [pimatic-mochad] 09/02 00:04:29 Rx PL House: P Func: All units off
# example2: 00:04:29.391 [pimatic-mochad]>
else if m = /^\d{2}\/\d{2}\s+(?:\d{2}:){2}\d{2}\s(Rx|Tx)\s+(RF|PL)\s+House:\s+([a-pA-P])\s+Func:\s+All\s+(units|lights)\s+(on|off)$/m.exec(lines)
event = {
protocol: m[2].toLowerCase(),
direction: m[1].toLowerCase(),
housecode: m[3].toLowerCase(),
unitcode: "*" + m[4],
state: (if m[5] is "On" then true else false)
}
env.logger.debug("Event: " + JSON.stringify(event))
@emit 'event', event
if event.direction is "tx" and @unitsContainer[event.housecode]
for unitcode, unit of @unitsContainer[event.housecode]
env.logger.debug("House #{event.housecode} unit #{unitcode} has state #{event.state}");
unit._setState(event.state)
# Handling simple on/off (RF-style)
# 11/30 17:57:12 Tx RF HouseUnit: A10 Func: On
# 11/30 17:57:24 Tx RF HouseUnit: A10 Func: Off
else if m = /^\d{2}\/\d{2}\s+(?:\d{2}:){2}\d{2}\s(Rx|Tx)\s+(RF|PL)\s+HouseUnit:\s+([a-pA-P])(\d{1,2})\s+Func:\s+(On|Off)/m.exec(lines)
event = {
protocol: m[2].toLowerCase()
direction: m[1].toLowerCase()
housecode: m[3].toLowerCase()
unitcode: parseInt(m[4], 10)
state: (if m[5] is "On" then true else false)
}
env.logger.debug("Event: " + JSON.stringify(event))
@emit 'event', event
if event.direction is "tx" and @unitsContainer[event.housecode] and unit = @unitsContainer[event.housecode][event.unitcode]
env.logger.debug("House #{event.housecode} unit #{event.unitcode} has state #{event.state}");
unit._setState(event.state)
# Handling simple on/off (PL-style)
# example: 05/30 20:59:20 Tx PL HouseUnit: P1
# example: 05/30 20:59:20 Tx PL House: P Func: On
# example2: 23:42:03.196 [pimatic-mochad] 09/01 23:42:03 Tx PL HouseUnit: P1
# example2: 23:42:03.196 [pimatic-mochad]>
# example2: 23:42:03.198 [pimatic-mochad] 09/01 23:42:03 Tx PL House: P Func: On
else if m = /^\d{2}\/\d{2}\s+(?:\d{2}:){2}\d{2}\s(?:Rx|Tx)\s+(?:RF|PL)\s+HouseUnit:\s+([a-pA-P])(\d{1,2})/m.exec(lines)
@lastSeen.housecode = m[1].toLowerCase()
@lastSeen.unitcode = parseInt(m[2], 10)
env.logger.debug("Event: " + JSON.stringify(@lastSeen))
if @lastSeen.housecode and @lastSeen.unitcode and m = /\d{2}\/\d{2}\s+(?:\d{2}:){2}\d{2}\s(Rx|Tx)\s+(RF|PL)\s+House:\s+([a-pA-P])\s+Func:\s+(On|Off)$/m.exec(lines)
event = {
protocol: m[2].toLowerCase()
direction: m[1].toLowerCase()
housecode: m[3].toLowerCase()
unitcode: null # filled later
state: (if m[4] is "On" then true else false)
}
if event.housecode == @lastSeen.housecode
event.unitcode = @lastSeen.unitcode
env.logger.debug("Event: " + JSON.stringify(event))
@emit 'event', event
if event.protocol in ["pl", "rf"] and event.direction is "tx" and @unitsContainer[event.housecode] and unit = @unitsContainer[event.housecode][event.unitcode]
unit._setState(event.state)
).bind(@)
).bind(@)).connect(port, host);
reconnector.on 'connect', ((connection) ->
env.logger.info("(re)Opened connection")
@connection = connection
@sendCommand("st")
).bind(@)
reconnector.on 'disconnect', ((err) ->
env.logger.error("Disconnected from #{@host}:#{@port}: " + err)
@connection = null;
).bind(@)
# ####sendCommand()
#
# #####params:
# * `connection`
# * `command`
sendCommand: (command) ->
Promise
.try((() ->
if @connection is null then throw new Error("No connection!")
env.logger.debug("Sending '#{command}'")
@connection.write(command + "\r\n")
).bind(@))
.catch((error) -> env.logger.error("Couldn't send command '#{command}': " + error))
# #### MochadSwitch class
class MochadSwitch extends env.devices.SwitchActuator
# ####constructor()
#
# #####params:
# * `deviceConfig`
#
constructor: (@Mochad, uconf) ->
@id = uconf.id
@name = uconf.name
@housecode = uconf.housecode.toLowerCase()
@unitcode = parseInt(uconf.unitcode, 10)
@protocol = uconf.protocol || "pl" # TODO Fixme: json-schema doesn't handle the protocol-default
env.logger.debug("Initiated unit with: housecode='#{@housecode}', unitcode='#{@unitcode}, id='#{@id}', name='#{@name}', protocol='#{@protocol}'")
super()
# ####changeStateTo()
#
# #####params:
# * `state`
#
changeStateTo: (state) ->
@Mochad.sendCommand("#{@protocol} #{@housecode}#{@unitcode} " + ( if state then "on" else "off" ))
# #### MochadDimmer class
class MochadDimmer extends MochadSwitch
# ####constructor()
#
# #####params:
# * `deviceConfig`
#
constructor: (@Mochad, uconf) ->
super @Mochad, uconf
@actions = _.merge @actions,
brighten:
description: "brighten the light"
dim:
description: "dim the light"
# TODO documentation says this is not required, but it actually is ...
template: "mochad-dimmer"
getTemplateName: -> @template
# ####changeLux()
#
# #####params:
# * `direaction`
#
changeLux: (direction) ->
@Mochad.sendCommand("#{@protocol} #{@housecode}#{@unitcode} " + ( if direction is "up" then "bright" else "dim" ))
brighten: () ->
@changeLux 'up'
dim: () ->
@changeLux 'down'
# TODO Needs to be implemented
class MochadActionProvider extends env.actions.ActionProvider
constructor: (@framework) ->
parseAction: (input, context) =>
mochadDevices = _(@framework.devices).values().filter(
(device) => device instanceof Mochad
).value()
if mochadDevices.length is 0 then return
match = null
device = null
commandTokens = null
m = M(input, context)
.match('tell ')
.matchDevice(mochadDevices, (m, d) =>
m.match(' to send ')
.matchStringWithVars((m, ct) =>
if device? and d? and device.id isnt d.id
context?.addError(""""#{input.trim()}" is ambiguous.""")
return
device = d
commandTokens = ct
match = m.getFullMatch()
)
)
if match
return {
token: match
nextInput: input.substring(match.length)
actionHandler: new MochadActionHandler(@framework, device, commandTokens)
}
else
return null
class MochadActionHandler extends env.actions.ActionHandler
constructor: (@framework, @device, @commandTokens) ->
executeAction: (simulate) =>
@framework.variableManager.evaluateStringExpression(@commandTokens).then( (command) =>
if simulate
# just return a promise fulfilled with a description about what we would do.
__("would send \"%s\"", command)
else
@device.sendCommand(command)
)
# TODO Needs to be implemented
class MochadPredicateProvider extends env.predicates.PredicateProvider
constructor: (@framework) ->
parsePredicate: (input, context) ->
mochadDevices = _(@framework.devices).values().filter(
(device) => device instanceof Mochad
).value()
if mochadDevices.length is 0 then return
match = null
device = null
direction = null
commandTokens = null
m = M(input, context)
.matchDevice(mochadDevices, (m, d) =>
m.match([' receives ', ' sends '], (m, s) ->
m.matchStringWithVars((m, ct) =>
if device? and d? and device.id isnt d.id
context?.addError(""""#{input.trim()}" is ambiguous.""")
return
device = d
direction = if s is " receives" then "rx" else "tx"
commandTokens = ct
match = m.getFullMatch()
)
)
)
if match
return {
token: match
nextInput: input.substring(match.length)
predicateHandler: new MochadPredicateHandler(@framework, device, direction, commandTokens)
}
else
return null
class MochadPredicateHandler extends env.predicates.PredicateHandler
constructor: (@framework, device, direction, commandTokens) ->
# ###Wrap up
myMochadPlugin = new MochadPlugin
return myMochadPlugin