forked from rg-engineering/ioBroker.semp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNodeRedSempGateway.js
469 lines (430 loc) · 17 KB
/
NodeRedSempGateway.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
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
const Gateway = require("./lib/semp/Gateway").Gateway;
class NodeRedSempGateway {
constructor(options) {
this.uuid = "ae245e42-033e-4f68-b48f-9170fbfbf186"
this.ipAddress = null
this.sempPort = 9765
this.sempName = "NodeRED SEMP Gateway"
this.sempManufacturer = "NodeRED"
this.logDebugMessages = false
if (typeof(options) != "undefined")
{
if (typeof(options.uuid) != "undefined")
{
this.uuid = options.uuid
}
else
{
console.warn("SEMP: Please specify an uuid if you have multiple instances of of this module running in your network.")
}
if (typeof(options.ipAddress) != "undefined")
{
this.ipAddress = options.ipAddress
}
if (typeof(options.sempPort) != "undefined")
{
this.sempPort = options.sempPort
}
if (typeof(options.sempName) != "undefined")
{
this.sempName = options.sempName
}
if (typeof(options.sempManufacturer) != "undefined")
{
this.sempManufacturer = options.sempManufacturer
}
}
this.registeredDevices = {};
this.registeredCallbacks = {};
this.ioBrokerMockAdaptor = {
log: {
trace: function(msg) {if (this.logDebugMessages) console.trace(msg)},
debug: function(msg) {if (this.logDebugMessages) console.debug(msg)},
info: function(msg) {console.info(msg)},
warn: function(msg) {console.warn(msg)},
error: function(msg) {console.error(msg)}
},
config: {
LogToCSV: false
},
_parent: {},
_callCallback: function(key, value)
{
if (typeof(this._parent.registeredCallbacks[key]) != "undefined")
this._parent.registeredCallbacks[key](value.val)
},
subscribeForeignStates: function(key)
{
// this.log.debug("ioBrokerMockAdaptor.subscribeForeignStates: key: " + key);
},
setForeignStateAsync: async function(key, value)
{
this.log.debug("ioBrokerMockAdaptor.setForeignStateAsync: key: " + key + " value: " + JSON.stringify(value));
this._callCallback(key, value)
},
getForeignStateAsync: async function(key)
{
// this.log.debug("ioBrokerMockAdaptor.getForeignStateAsync: key: " + key);
return null;
},
setForeignState: function(key, value)
{
this.log.debug("ioBrokerMockAdaptor.setForeignState: key: " + key + " value: " + JSON.stringify(value));
this._callCallback(key, value)
},
getForeignState: async function(key)
{
// this.log.debug("ioBrokerMockAdaptor.getForeignState: key: " + key);
return null;
},
subscribeStates: function(key)
{
// this.log.debug("ioBrokerMockAdaptor.subscribeStates: key: " + key);
},
setStateAsync: async function(key, value)
{
this.log.debug("ioBrokerMockAdaptor.setStateAsync: key: " + key + " value: " + JSON.stringify(value));
this._callCallback(key, value)
},
getStateAsync: async function(key)
{
// this.log.debug("ioBrokerMockAdaptor.getStateAsync: key: " + key);
return null;
},
setState: function(key, value)
{
this.log.debug("ioBrokerMockAdaptor.setState: key: " + key + " value: " + JSON.stringify(value));
this._callCallback(key, value)
},
getState: async function(key)
{
// this.log.debug("ioBrokerMockAdaptor.getState: key: " + key);
return null;
},
getObjectAsync: async function(key)
{
// this.log.debug("ioBrokerMockAdaptor.getObjectAsync: key: " + key);
return null;
},
setObjectNotExistsAsync: async function(key, obj)
{
// this.log.debug("ioBrokerMockAdaptor.setObjectNotExistsAsync: key: " + key + " obj: " + JSON.stringify(obj));
}
}
this.ioBrokerMockAdaptor._parent = this;
}
callCallback(key, value)
{
if (typeof(this.registeredCallbacks[key]) != "undefined")
this.registeredCallbacks[key](value.val)
}
findIPv4IPs() {
// Get all network devices
const ifaces = require('os').networkInterfaces();
var net_devs = [];
for (var dev in ifaces) {
if (ifaces.hasOwnProperty(dev)) {
// Read IPv4 address properties of each device by filtering for the IPv4 external interfaces
ifaces[dev].forEach(details => {
if (!details.internal && details.family === 'IPv4') {
net_devs.push({name: dev, ipaddr: details.address});
}
});
}
}
return net_devs;
}
async start() {
if (this.ipAddress == null)
{
let ips = this.findIPv4IPs();
console.log("Found IPs: ", ips);
if (ips.length > 1)
{
console.warn("SEMP: found more than one IP address. Taking the first ethernet device.");
for (const ip of ips) {
if (ip.name.indexOf("en") === 0 || ip.name.indexOf("eth") === 0)
{
this.ipAddress = ip.ipaddr
console.log("SEMP: Using " + this.ipAddress + " from device " + ip.name)
break
}
}
}
else if (ips.length === 1)
{
this.ipAddress = ips[0].ipaddr
console.log("SEMP: Using " + this.ipAddress + " from device " + ips[0].name)
}
}
else
{
console.log("SEMP: Using configured " + this.ipAddress)
}
this.gw = new Gateway(this.ioBrokerMockAdaptor,
this.uuid, this.ipAddress, this.sempPort, this.sempName, this.sempManufacturer);
if (this.gw != null) {
await this.gw.start();
console.debug("Started all!");
}
}
addDevice(device, periods)
{
/*
Device.js IO Broker admin interface
DeviceIsActive devices[id].IsActive
DeviceID devices[id].ID
DeviceVendor devices[id].Vendor
DeviceName devices[id].Name
DeviceType devices[id].Type
<xs:enumeration value="AirConditioning"/>
<xs:enumeration value="Charger"/>
<xs:enumeration value="DishWasher"/>
<xs:enumeration value="Dryer"/>
<xs:enumeration value="ElectricVehicle"/>
<xs:enumeration value="EVCharger"/>
<xs:enumeration value="Freezer"/>
<xs:enumeration value="Fridge"/>
<xs:enumeration value="Heater"/>
<xs:enumeration value="HeatPump"/>
<xs:enumeration value="Motor"/>
<xs:enumeration value="Pump"/>
<xs:enumeration value="WashingMachine"/>
<xs:enumeration value="Other"/>
DeviceSerialnumber devices[id].SerialNr
DeviceMaxPower devices[id].MaxPower
DeviceMinPower devices[id].MinPower
DeviceInterruptionAllowed devices[id].InterruptionsAllowed
DeviceMinOnTime devices[id].MinOnTime
DeviceMaxOnTime devices[id].MaxOnTime
DeviceMinOffTime devices[id].MinOffTime
DeviceMaxOffTime devices[id].MaxOffTime
DeviceMeasurementMethod devices[id].MeasurementMethod
<xs:enumeration value="Measurement"/>
<xs:enumeration value="Estimation"/>
<xs:enumeration value="None"/>
DeviceOIDPower devices[id].OID_Power ioBroker Property ID for measured power (subscribed only when MeasurementMethod == "Measurement")
DeviceStatusDetectionType devices[id].StatusDetection
<option value="SeparateOID" class="translate">SeparateOID</option> --> OID_Status is used
<option value="FromPowerValue" class="translate">FromPowerValue</option> --> Determine state from power value
<option value="AlwaysOn" class="translate">AlwaysOn</option>
DeviceOIDStatus devices[id].OID_Status ioBroker Property ID On or Off, represents the current state of the device
DeviceHasOIDSwitch devices[id].HasOIDSwitch
DeviceOIDSwitch devices[id].OID_Switch ioBroker Property ID the outgoing new state, as set by the Energy Manager
DeviceTimerActive devices[id].TimerActive
DeviceMeasurementUnit devices[id].MeasurementUnit default assumption: W
DeviceStatusDetectionLimit devices[id].StatusDetectionLimit
DeviceStatusDetectionLimitTimeOn devices[id].StatusDetectionLimitTimeOn
DeviceStatusDetectionLimitTimeOff devices[id].StatusDetectionLimitTimeOff
DeviceStatusDetectionMinRunTime devices[id].StatusDetectionMinRunTime
DeviceSwitchOffAtEndOfTimer devices[id].SwitchOffAtEndOfTimer
//cancel request: see issue #14
DeviceTimerCancelIfNotOn devices[id].TimerCancelIfNotOn
DeviceTimerCancelIfNotOnTime devices[id].TimerCancelIfNotOnTime
*/
let statusDetectionMethods = {
FromOnOffStatus: "SeparateOID",
FromPowerValue: "FromPowerValue",
AlwaysOn: "AlwaysOn"
}
if (typeof(statusDetectionMethods[device.statusDetection]) === "undefined")
{
console.warn("SEMP: addDevice: device.statusDetection '" + device.statusDetection + "' is not supported. Supported are " + JSON.stringify(Object.keys(statusDetectionMethods)));
return
}
this.gw.addDevice({
ID: device.id,
Name: device.name,
Type: device.type,
SerialNr: device.serial,
Vendor: device.vendor,
MaxPower: device.maxPowerConsumption_W,
MinPower: device.minPowerConsumption_W,
InterruptionsAllowed: device.interruptionsAllowed,
MeasurementMethod: device.measurementMethod,
StatusDetection: statusDetectionMethods[device.statusDetection],
HasOIDSwitch: device.isSwitchable,
TimerActive: typeof(periods) !== "undefined",
OID_Power: "not_used", // statte property identifier of ioBroker
OID_Status: "not_used", // statte property identifier of ioBroker
EnergyRequestPeriods: periods
});
this.registeredDevices[device.id] = device;
return device.id;
}
/*
//energy request list
table EnergyRequestPeriods devices[id].EnergyRequestPeriods
-> ID
-> Days
-> EarliestStartTime
-> LatestEndTime
-> MinRunTime
-> MaxRunTime
*/
setPlanningRequest(deviceID, periods)
{
if (typeof(this.registeredDevices[deviceID]) === "undefined")
{
console.warn("SEMP: setPlanningRequest: Device " + deviceID + " does not exist!")
return
}
if (typeof(periods.length) === "undefined")
{
// only one period was given directly, not as array.
periods = [periods]
}
let energyRequestPeriods = []
for (const period of periods)
{
let reqPeriod = {
ID: deviceID,
EarliestStartTime: period.earliestStartTime,
LatestEndTime: period.latestEndTime,
MinRunTime: period.minRunTime,
MaxRunTime: period.maxRunTime,
Days: "everyDay"
}
if (typeof(period.earliestStartTime) === "undefined" && typeof(period.earliestStartIn_s !== "undefined"))
reqPeriod.EarliestStartTime = period.earliestStartIn_s
if (typeof(period.latestEndTime) === "undefined" && typeof(period.latestEndIn_s !== "undefined"))
reqPeriod.LatestEndTime = period.latestEndIn_s
if (typeof(period.minRunTime) === "undefined" && typeof(period.minRunDuration_s !== "undefined"))
reqPeriod.MinRunTime = period.minRunDuration_s
if (typeof(period.maxRunTime) === "undefined" && typeof(period.maxRunDuration_s !== "undefined"))
reqPeriod.MaxRunTime = period.maxRunDuration_s
if (typeof(reqPeriod.EarliestStartTime) === "undefined")
{
console.warn("SEMP: setPlanningRequest: Device " + deviceID + " Either earliestStartTime or earliestStartIn_s has to be given in periods object/array of objects")
return
}
if (typeof(reqPeriod.LatestEndTime) === "undefined")
{
console.warn("SEMP: setPlanningRequest: Device " + deviceID + " Either latestEndTime or latestEndIn_s has to be given in periods object/array of objects")
return
}
if (typeof(reqPeriod.MinRunTime) === "undefined")
{
console.warn("SEMP: setPlanningRequest: Device " + deviceID + " Either minRunTime or minRunDuration_s has to be given in periods object/array of objects")
return
}
if (typeof(reqPeriod.MaxRunTime) === "undefined")
{
console.warn("SEMP: setPlanningRequest: Device " + deviceID + " Either maxRunTime or maxRunDuration_s has to be given in periods object/array of objects")
return
}
energyRequestPeriods.push(reqPeriod)
}
this.gw.deleteDevice(deviceID)
this.addDevice(this.registeredDevices[deviceID], energyRequestPeriods)
}
setCallback(deviceID, eventName, callback)
{
let knownEvents = {
RecommendedOnOffStatus: "RecommendedState",
CurrentState: "State"
}
if (typeof(this.registeredDevices[deviceID]) === "undefined")
{
console.warn("SEMP: addCallback: Device " + deviceID + " does not exist!")
return
}
if (typeof(knownEvents[eventName]) === "undefined")
{
console.warn("SEMP: addCallback: eventName '" + eventName + "' is not defined. Please use " + JSON.stringify(Object.keys(knownEvents)))
return
}
let callbackID = "Devices." + this.registeredDevices[deviceID].name + "." + knownEvents[eventName]
this.registeredCallbacks[callbackID] = callback
}
setPower_W(deviceID, power_W)
{
if (typeof(this.registeredDevices[deviceID]) === "undefined")
{
console.warn("SEMP: setPower_W: Device " + deviceID + " does not exist!")
return
}
this.gw.setPowerDevice(deviceID, power_W)
}
setOnOffStatus(deviceID, status)
{
if (typeof(this.registeredDevices[deviceID]) === "undefined")
{
console.warn("SEMP: setOnOffStatus: Device " + deviceID + " does not exist!")
return
}
this.gw.setOnOffDevice(deviceID, status)
}
}
var instance = null
module.exports = {
init: function(options)
{
if (instance !== null)
{
console.warn("SEMP: already initialized.");
return;
}
instance = new NodeRedSempGateway(options);
instance.start();
},
dispose: function()
{
if (instance === null)
{
console.warn("SEMP: dispose: NOT initialized.");
return;
}
instance.gw.stop();
instance = null
},
addDevice: function(device)
{
if (instance === null)
{
console.warn("SEMP: addDevice: NOT initialized.");
return;
}
return instance.addDevice(device);
},
setPlanningRequest: function(deviceID, periods)
{
if (instance === null)
{
console.warn("SEMP: setPlanningRequest: NOT initialized.");
return;
}
instance.setPlanningRequest(deviceID, periods);
},
setCallback: function(deviceID, eventName, callback)
{
if (instance === null)
{
console.warn("SEMP: addCallback: NOT initialized.");
return;
}
instance.setCallback(deviceID, eventName, callback);
},
setPower_W: function(deviceID, power_W)
{
if (instance === null)
{
console.warn("SEMP: setPower_W: NOT initialized.");
return;
}
instance.setPower_W(deviceID, power_W);
},
setOnOffStatus: function(deviceID, status)
{
if (instance === null)
{
console.warn("SEMP: setOnOffStatus: NOT initialized.");
return;
}
instance.setOnOffStatus(deviceID, status);
},
setLogDebugMessages: function(enable)
{
instance.logDebugMessages = enable
}
}