forked from thexperiments/pimatic-harmonyhub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathharmonyhub.coffee
executable file
·316 lines (245 loc) · 11.5 KB
/
harmonyhub.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
# #Plugin template
# This is an plugin template and mini tutorial for creating pimatic plugins. It will explain the
# basics of how the plugin system works and how a plugin should look like.
# ##The plugin code
# Your plugin must export a single function, that takes one argument and returns a instance of
# your plugin class. The parameter is an environment object containing all pimatic related functions
# and classes. See the [startup.coffee](http://sweetpi.de/pimatic/docs/startup.html) for details.
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
# Require the bluebird promise library
Promise = env.require 'bluebird'
# Include you own dependencies with nodes global require function:
#
# someThing = require 'someThing'
#
HarmonyHubClient = require 'harmonyhubjs-client'
HarmonyHubDiscover = require 'harmonyhubjs-discover'
class HarmonyHub 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) =>
# get the device config schemas
deviceConfigDef = require("./device-config-schema")
env.logger.info("Starting pimatic-harmonyhub plugin")
#env.logger.logDebug = true
@hubInstancePool = []
@framework.deviceManager.registerDeviceClass("HarmonyHubPowerSwitch", {
configDef: deviceConfigDef.HarmonyHubPowerSwitch,
createCallback: (config, lastState) =>
return new HarmonyHubPowerSwitch(config, @, lastState)
})
@framework.deviceManager.registerDeviceClass("HarmonyHubButtonsDevice", {
configDef: deviceConfigDef.HarmonyHubButtonsDevice,
createCallback: (config, lastState) =>
return new HarmonyHubButtonsDevice(config, @)
})
@framework.deviceManager.registerDeviceClass("HarmonyHubActivitiesButtonsDevice", {
configDef: deviceConfigDef.HarmonyHubActivitiesButtonsDevice,
createCallback: (config, lastState) =>
return new HarmonyHubActivitiesButtonsDevice(config, @)
})
@framework.deviceManager.on 'discover', () =>
env.logger.debug("Starting discovery")
@framework.deviceManager.discoverMessage(
'pimatic-harmonyhub', "Searching for devices"
)
@HarmonyHubDiscoverInstance = new HarmonyHubDiscover(61991)
@HarmonyHubDiscoverInstance.on 'online', (hub) =>
@hubIP = hub.ip
env.logger.debug("Discovered hub@#{@hubIP}")
HarmonyHubClient(@hubIP).then (hubInstance) =>
@hubIP = @hubIP
env.logger.debug("Getting available commands for hub@#{@hubIP}")
hubInstance.getAvailableCommands().then (commands) =>
devices = commands.device
env.logger.debug("looking for device commands on hub@#{@hubIP}")
for currentDevice in devices
controlGroups = currentDevice.controlGroup
env.logger.debug("looking for control groups on hub@#{@hubIP}")
for currentControlGroup in controlGroups
#create a Buttons device for each ControlGroup
deviceFunctions = currentControlGroup.function
buttonsArray = []
commandType = ""
env.logger.debug("found controll group #{currentControlGroup.name} on hub@#{@hubIP}")
deviceConfig =
class: "HarmonyHubButtonsDevice"
name: "#{currentDevice.label}(#{currentControlGroup.name})"
id: "#{currentDevice.label.replace(" ","-").toLowerCase()}-#{currentControlGroup.name.replace(" ","-").toLowerCase()}"
hubIP: @hubIP
deviceId: currentDevice.id
commandType: ""
for currentDeviceFunction in deviceFunctions
deviceAction = JSON.parse(currentDeviceFunction.action)
#fill the buttons with the different functions
buttonConfig =
id : "#{currentDevice.label.replace(" ","-").toLowerCase()}-#{currentControlGroup.name.replace(" ","-").toLowerCase()}-#{currentDeviceFunction.name.replace(" ","-").toLowerCase()}"
text : currentDeviceFunction.label
command : deviceAction.command
buttonsArray.push(buttonConfig)
deviceConfig.commandType = deviceAction.type
deviceConfig.buttons = buttonsArray
#notify about the discovered device
@framework.deviceManager.discoveredDevice(
'pimatic-harmonyhub', "#{deviceConfig.name}", deviceConfig
)
env.logger.debug("Getting available activites for hub@#{@hubIP}")
hubInstance.getActivities().then (activities) =>
env.logger.debug("received acivities: #{JSON.stringify(activities)} ")
deviceConfig =
class: "HarmonyHubActivitiesButtonsDevice"
name: "Acitvities on #{@hubIP}"
id: "activities-#{@hubIP.replace(".","-").toLowerCase()}"
hubIP: @hubIP
buttonsArray = []
for currentActivity in activities
env.logger.debug("found activity #{currentActivity.label} on hub@#{@hubIP}")
buttonConfig =
id : "activities-button-#{currentActivity.label.replace(" ","-").toLowerCase()}"
text : currentActivity.label
activityId : currentActivity.id
buttonsArray.push(buttonConfig)
deviceConfig.buttons = buttonsArray
#notify about the discovered device
@framework.deviceManager.discoveredDevice(
'pimatic-harmonyhub', "#{deviceConfig.name}", deviceConfig
)
@HarmonyHubDiscoverInstance.start()
stopDiscovery = () =>
@HarmonyHubDiscoverInstance.stop()
setTimeout stopDiscovery, 20000
sendHarmonyHubCommand: (hubIP, command, commandType, deviceId) =>
@hubIP = hubIP
@command = command
@commandType = commandType
@deviceId = deviceId
@getHubInstance(@hubIP).then () =>
action =
command: @command
type: @commandType
deviceId: "#{@deviceId}"
env.logger.debug("sending command #{JSON.stringify(action)} to #{@hubInstance.toString()}")
@encodedAction = JSON.stringify(action).replace(/\:/g, '::')
requestPromise = @hubInstance.send('holdAction', 'action=' + @encodedAction + ':status=press').then () =>
@hubInstance.send('holdAction', 'action=' + @encodedAction + ':status=release')
return requestPromise
startHarmonyHubActivity: (hubIP, activityId) =>
@hubIP = hubIP
@activityId = activityId
@getHubInstance(@hubIP).then () =>
env.logger.debug("sending activity #{@activityId}")
requestPromise = @hubInstance.startActivity(@activityId)
return requestPromise
getHubInstance: (@hubIP) ->
if @hubInstancePool[@hubIP]
env.logger.debug("hub instance found for #{@hubIP}")
@hubInstance = @hubInstancePool[@hubIP]
requestPromise = Promise.resolve(true)
else
env.logger.debug("no hub instance found yet for #{@hubIP}")
requestPromise = HarmonyHubClient(@hubIP).then (hubInstance) =>
@hubInstance = hubInstance
@hubInstance._xmppClient.on 'offline', ()=>
env.logger.debug("hub instance for #{@hubIP} went offline, recreating")
@hubInstancePool[@hubIP] = null
@getHubInstance(@hubIP)
@hubInstancePool[@hubIP] = hubInstance
return requestPromise
_generateDeviceId: (prefix, lastId = null) ->
start = 1
if lastId?
m = lastId.match /.*-([0-9]+)$/
start = +m[1] + 1 if m? and m.length is 2
for x in [start...1000] by 1
result = "#{prefix}-#{x}"
matched = @framework.deviceManager.devicesConfig.some (element, iterator) ->
element.id is result
return result if not matched
class HarmonyHubPowerSwitch extends env.devices.PowerSwitch
#
constructor: (@config, @plugin, lastState) ->
@name = @config.name
@id = @config.id
@hubIP = @config.hubIP
@commandType = @config.commandType
@onCommand = @config.onCommand
@offCommand = @config.offCommand
@deviceId = @config.deviceId
super()
destroy: () ->
@requestPromise.cancel() if @requestPromise?
super()
getState: () ->
#not currently implemented
return Promise.resolve @_state
changeStateTo: (state) ->
env.logger.debug "setting state to #{state}"
command = if state then @onCommand else @offCommand
@requestPromise = @plugin.sendHarmonyHubCommand(@hubIP, command, @commandType, @deviceId).then(() =>
env.logger.debug "setting state success"
@_setState(state)
).catch((error) =>
env.logger.error("Unable to set power state of device: " + error.toString())
)
class HarmonyHubButtonsDevice extends env.devices.ButtonsDevice
constructor: (@config, @plugin) ->
@name = @config.name
@id = @config.id
@hubIP = @config.hubIP
@commandType = @config.commandType
@buttons = @config.buttons
@deviceId = @config.deviceId
super(@config)
destroy: () ->
@requestPromise.cancel() if @requestPromise?
super()
buttonPressed: (buttonId) ->
for b in @config.buttons
if b.id is buttonId
@_lastPressedButton = b.id
@emit 'button', b.id
command = b.command
@requestPromise = @plugin.sendHarmonyHubCommand(@hubIP, command, @commandType, @deviceId).then(() =>
env.logger.debug "sending command state success"
).catch((error) =>
env.logger.error("Unable to send command to device: " + error.toString())
)
return @requestPromise
throw new Error("No button with the id #{buttonId} found")
class HarmonyHubActivitiesButtonsDevice extends env.devices.ButtonsDevice
constructor: (@config, @plugin) ->
@name = @config.name
@id = @config.id
@hubIP = @config.hubIP
@buttons = @config.buttons
super(@config)
destroy: () ->
@requestPromise.cancel() if @requestPromise?
super()
buttonPressed: (buttonId) ->
for b in @config.buttons
if b.id is buttonId
@_lastPressedButton = b.id
@emit 'button', b.id
activityId = b.activityId
@requestPromise = @plugin.startHarmonyHubActivity(@hubIP, activityId).then(() =>
env.logger.debug "starting activity command state success"
).catch((error) =>
env.logger.error("Unable to send start activity to device: " + error.toString())
)
return @requestPromise
throw new Error("No button with the id #{buttonId} found")
# ###Finally
# Create a instance of my plugin
myHarmonyHub = new HarmonyHub
# and return it to the framework.
return myHarmonyHub