forked from Krillle/homebridge-signalk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
executable file
·1216 lines (1021 loc) · 50.1 KB
/
index.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
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const _ = require('lodash');
var httpLog = require('debug')('homebridge-signalk:http');
var wsLog = require('debug')('homebridge-signalk:websocket');
var request = require('request');
var http = require('http');
var _url = require('url');
var websocket = require("ws");
var Accessory, Service, Characteristic, UUIDGen;
const urlPath = 'signalk/v1/api/vessels/self/'
const wsPath = 'signalk/v1/stream?subscribe=none' // none will stream only the heartbeat, until the client issues subscribe messages in the WebSocket stream
// EmpirBus NXT + Venus GX switches and dimmer
//
// Key path according to EmpirBus Application Specific PGN Data Model 2 (2x word + 8x bit) per instance:
// 2x dimmer values 0 = off .. 1000 = 100%, 8x switch values 0 = off / 1 = on
//
// electrical.switches.empirBusNxt-instance<NXT component instance 0..49>-switch<#1..8>.state
// electrical.switches.empirBusNxt-instance<NXT component instance 0..49>-dimmer<#1..2>.state
const controlsPath = 'electrical.switches'
const empirBusIdentifier = 'empirBusNxt'
const venusRelaisIdentifier = 'venus'
const controlsPutPath = 'electrical/switches/'
const switchOnValues = [ 'true', 'on', 'low power', 'passthrough', '1' ] // All Signal K values which represent a switch is "on"
// Victron Venus GX Chargers
const chargersPath = 'electrical.chargers'
const chargersDevices = [
{ key : 'mode' , displayName : 'Charger Mode' , deviceType : 'switch'},
{ key : 'capacity.stateOfCharge' , displayName : 'Charger SOC' , deviceType : 'batterySOC'}
];
// Environment temperatures + humidity
const environmentPath = 'environment'
const environments = [
{ key : 'outside.temperature' , displayName : 'Outside' , deviceType : 'temperature'},
{ key : 'inside.temperature' , displayName : 'Inside' , deviceType : 'temperature'},
{ key : 'inside.engineRoom.temperature' , displayName : 'Engine Room' , deviceType : 'temperature'},
{ key : 'inside.mainCabin.temperature' , displayName : 'Main Cabin' , deviceType : 'temperature'},
{ key : 'inside.refrigerator.temperature' , displayName : 'Refrigerator' , deviceType : 'temperature'},
{ key : 'inside.freezer.temperature' , displayName : 'Freezer' , deviceType : 'temperature'},
{ key : 'inside.heating.temperature' , displayName : 'Heating' , deviceType : 'temperature'},
{ key : 'water.temperature' , displayName : 'Water' , deviceType : 'temperature'},
{ key : 'cpu.temperature' , displayName : 'Raspberry Pi' , deviceType : 'temperature'},
{ key : 'outside.humidity' , displayName : 'Outside' , deviceType : 'humidity'},
{ key : 'inside.humidity' , displayName : 'Inside' , deviceType : 'humidity'},
{ key : 'inside.engineRoom.relativeHumidity' , displayName : 'Engine Room' , deviceType : 'humidity'},
{ key : 'inside.mainCabin.relativeHumidity' , displayName : 'Main Cabin' , deviceType : 'humidity'},
{ key : 'inside.refrigerator.relativeHumidity' , displayName : 'Refrigerator' , deviceType : 'humidity'},
{ key : 'inside.freezer.relativeHumidity' , displayName : 'Freezer' , deviceType : 'humidity'},
{ key : 'inside.heating.relativeHumidity' , displayName : 'Heating' , deviceType : 'humidity'}
];
// Tanks
const tanksPath = 'tanks'
const defaultLowFreshWaterLevel = 25.0
const defaultHighWasteWaterLevel = 75.0
const defaultHighBlackWaterLevel = 75.0
const defaultLowFuelLevel = 50.0
const defaultLowLubricationLevel = 50.0
const defaultLowLiveWellLevel = 50.0
const defaultLowGasLevel = 50.0
const defaultLowBallastLevel = 50.0
// Batteries
const batteriesPath = 'electrical.batteries'
const defaultEmptyBatteryVoltage = 22
const defaultLowBatteryVoltage = 23
const defaultFullBatteryVoltage = 26
const defaultChargingBatteryVoltage = 27
// Engine data
const enginePath = 'propulsion'
const engines = [
{ key : 'port.temperature' , displayName : 'Engine port' , deviceType : 'temperature'},
{ key : 'starboard.temperature' , displayName : 'Engine starboard' , deviceType : 'temperature'}
];
var errorHandler = (error) => { if ( error ) {
platform.log('Device unreachable:', error.message)
} else {
platform.log('Ok')
}
};
module.exports = function(homebridge) {
// console.log("homebridge API version: " + homebridge.version);
// Accessory must be created from PlatformAccessory Constructor
Accessory = homebridge.platformAccessory;
// Service and Characteristic are from hap-nodejs
Service = homebridge.hap.Service;
Characteristic = homebridge.hap.Characteristic;
UUIDGen = homebridge.hap.uuid;
// For platform plugin to be considered as dynamic platform plugin,
// registerPlatform(pluginName, platformName, constructor, dynamic), dynamic must be true
homebridge.registerPlatform("homebridge-signalk", "SignalK", SignalKPlatform, true);
}
// Platform constructor
// config may be null
// api may be null if launched from old homebridge version
function SignalKPlatform(log, config, api) {
log("SignalKPlatform Init");
if (!(config)) { log ("No Signal K configuration found"); return; }
if (!(config.host)) { log ("No Signal K host configuration found"); return; }
var platform = this;
this.log = log;
this.config = config;
this.accessories = new Map();
this.updateSubscriptions = new Map (); // Devices to update on WebSocket
this.url = 'http' + (config.ssl ? 's' : '') + '://' + config.host + '/' + urlPath;
this.wsl = 'ws' + (config.ssl ? 's' : '') + '://' + config.host + '/' + wsPath;
let wsOptions = {}
if (config.securityToken) {
wsOptions.headers = { 'Authorization': 'JWT ' + config.securityToken }
this.securityToken = config.securityToken
}
this.ws = new websocket(this.wsl, "ws", wsOptions);
this.wsInitiated = false;
this.emptyBatteryVoltage = Number(config.emptyBatteryVoltage) || defaultEmptyBatteryVoltage;
this.lowBatteryVoltage = Number(config.lowBatteryVoltage) || defaultLowBatteryVoltage;
this.fullBatteryVoltage = Number(config.fullBatteryVoltage) || defaultFullBatteryVoltage;
this.chargingBatteryVoltage = Number(config.chargingBatteryVoltage) || defaultChargingBatteryVoltage;
// this.batteryStateOfCharge = {
// (voltage) => (Number(voltage) - this.emptyBatteryVoltage) / (this.fullBatteryVoltage - this.emptyBatteryVoltage) * 100
// }
this.batteryWarnCondition = {
low : (voltage) => Number(voltage) <= this.lowBatteryVoltage,
charging : (voltage) => Number(voltage) >= this.chargingBatteryVoltage
}
this.lowFreshWaterLevel = Number(config.lowFreshWaterLevel) || defaultLowFreshWaterLevel;
this.highWasteWaterLevel = Number(config.highWasteWaterLevel) || defaultHighWasteWaterLevel;
this.highBlackWaterLevel = Number(config.highBlackWaterLevel) || defaultHighBlackWaterLevel;
this.lowFuelLevel = Number(config.lowFuelLevel) || defaultLowFuelLevel;
this.lowLubricationLevel = Number(config.lowLubricationLevel) || defaultLowLubricationLevel;
this.lowLiveWellLevel = Number(config.lowLiveWellLevel) || defaultLowLiveWellLevel;
this.lowGasLevel = Number(config.lowGasLevel) || defaultLowGasLevel;
this.lowBallastLevel = Number(config.lowBallastLevel) || defaultLowBallastLevel;
this.tankWarnCondition = {
freshWater : (level) => Number(level) * 100 <= this.lowFreshWaterLevel,
wasteWater : (level) => Number(level) * 100 >= this.highWasteWaterLevel,
blackWater : (level) => Number(level) * 100 >= this.highBlackWaterLevel,
fuel : (level) => Number(level) * 100 <= this.lowFuelLevel,
lubrication : (level) => Number(level) * 100 <= this.lowLubricationLevel,
liveWell : (level) => Number(level) * 100 <= this.lowLiveWellLevel,
gas : (level) => Number(level) * 100 <= this.lowGasLevel,
ballast : (level) => Number(level) * 100 <= this.lowBallastLevel
}
// this.requestServer = http.createServer(function(request, response) {
// if (request.url === "/add") {
// this.addAccessory(new Date().toISOString());
// response.writeHead(204);
// response.end();
// }
//
// if (request.url == "/reachability") {
// this.updateAccessoriesReachability();
// response.writeHead(204);
// response.end();
// }
//
// if (request.url == "/remove") {
// this.removeAccessory();
// response.writeHead(204);
// response.end();
// }
// }.bind(this));
//
// this.requestServer.listen(18081, function() {
// platform.log("Server Listening...");
// });
if (api) {
// Save the API object as plugin needs to register new accessory via this object
this.api = api;
// Listen to event "didFinishLaunching", this means homebridge already finished loading cached accessories.
// Platform Plugin should only register new accessory that doesn't exist in homebridge after this event.
// Or start discover new accessories.
this.api.on('didFinishLaunching', function() {
platform.log("Did finish launching");
// Remove not reachable accessories: cached accessories no more present in Signal K
platform.log("Checking for unreachable devices");
platform.accessories.forEach((accessory, key, map) => {
platform.checkKey(accessory.context.path, (error, result) => {
if (error && result == 'N/A' && config.removeDevicesNotPresent || !this.noignoredPath(accessory.context.path)) {
platform.log(`${accessory.displayName} not present or ignored`);
platform.removeAccessory(accessory);
}
})
});
// Start accessories value updating
platform.InitiateWebSocket()
this.wsInitiated = true;
// Addd new accessories in Signal K
platform.log("Looking for new accessories");
platform.autodetectNewAccessories()
}.bind(this));
}
}
// Function invoked when homebridge tries to restore cached accessory.
// Developer can configure accessory at here (like setup event handler).
// Update current value.
SignalKPlatform.prototype.configureAccessory = function(accessory) {
this.log("Configure Accessory", accessory.displayName);
var platform = this;
// Set the accessory to reachable if plugin can currently process the accessory,
// otherwise set to false and update the reachability later by invoking
// accessory.updateReachability()
this.checkKey(accessory.context.path, (error, result) => {
if (error) {
platform.log(`${accessory.displayName} not reachable`);
accessory.reachable = false;
} else {
platform.log(`${accessory.displayName} is reachable`);
accessory.reachable = true;
}
})
// FIXME: Ignored paths are added anyway
// FIXME: Results in crash ws updates when ignored or unreachable device is deleted afterwards
// Add Device Services
switch(accessory.context.deviceType) {
case 'switch':
this.addSwitchServices(accessory);
break;
case 'dimmer':
this.addDimmerServices(accessory);
break;
case 'temperature':
this.addTemperatureServices(accessory);
break;
case 'humidity':
this.addHumidityServices(accessory);
break;
case 'tank':
this.addTankServices(accessory);
break;
case 'battery' || 'charger':
this.addVoltageBatteryServices(accessory);
break;
case 'batterySOC':
this.addSOCBatteryServices(accessory);
break;
case 'leakSensor':
this.addLeakServices(accessory);
break;
}
this.accessories.set(accessory.context.path, accessory);
}
// Handler will be invoked when user try to config your plugin.
// Callback can be cached and invoke when necessary.
SignalKPlatform.prototype.configurationRequestHandler = function(context, request, callback) {
this.log("Context: ", JSON.stringify(context));
this.log("Request: ", JSON.stringify(request));
// Check the request response
if (request && request.response && request.response.inputs && request.response.inputs.name) {
this.addAccessory(request.response.inputs.name);
// Invoke callback with config will let homebridge save the new config into config.json
// Callback = function(response, type, replace, config)
// set "type" to platform if the plugin is trying to modify platforms section
// set "replace" to true will let homebridge replace existing config in config.json
// "config" is the data platform trying to save
callback(null, "platform", true, {"platform":"SignalKPlatform", "otherConfig":"SomeData"});
return;
}
// - UI Type: Input
// Can be used to request input from user
// User response can be retrieved from request.response.inputs next time
// when configurationRequestHandler being invoked
var respDict = {
"type": "Interface",
"interface": "input",
"title": "Add Accessory",
"items": [
{
"id": "name",
"title": "Name",
"placeholder": "Fancy Light"
}//,
// {
// "id": "pw",
// "title": "Password",
// "secure": true
// }
]
}
// - UI Type: List
// Can be used to ask user to select something from the list
// User response can be retrieved from request.response.selections next time
// when configurationRequestHandler being invoked
// var respDict = {
// "type": "Interface",
// "interface": "list",
// "title": "Select Something",
// "allowMultipleSelection": true,
// "items": [
// "A","B","C"
// ]
// }
// - UI Type: Instruction
// Can be used to ask user to do something (other than text input)
// Hero image is base64 encoded image data. Not really sure the maximum length HomeKit allows.
// var respDict = {
// "type": "Interface",
// "interface": "instruction",
// "title": "Almost There",
// "detail": "Please press the button on the bridge to finish the setup.",
// "heroImage": "base64 image data",
// "showActivityIndicator": true,
// "showNextButton": true,
// "buttonText": "Login in browser",
// "actionURL": "https://google.com"
// }
// Plugin can set context to allow it track setup process
context.ts = "Hello";
// Invoke callback to update setup UI
callback(respDict);
}
// // Sample function to show how developer can add accessory dynamically from outside event
// SignalKPlatform.prototype.addAccessory = function(accessoryName) {
// this.log("Add Accessory");
// var platform = this;
// var uuid;
//
// uuid = UUIDGen.generate(accessoryName);
//
// var newAccessory = new Accessory(accessoryName, uuid);
// newAccessory.on('identify', function(paired, callback) {
// platform.log(newAccessory.displayName, "Identify!!!");
// callback();
// });
// // Plugin can save context on accessory to help restore accessory in configureAccessory()
// // newAccessory.context.something = "Something"
//
// // Make sure you provided a name for service, otherwise it may not visible in some HomeKit apps
// newAccessory.addService(Service.Lightbulb, "Test Light")
// .getCharacteristic(Characteristic.On)
// .on('set', function(value, callback) {
// platform.log(newAccessory.displayName, "Light -> " + value);
// callback();
// });
//
// this.accessories.push(newAccessory);
// this.api.registerPlatformAccessories("homebridge-signalk", "SignalK", [newAccessory]);
// }
// Add accessory
SignalKPlatform.prototype.addAccessory = function(accessoryName, identifier, path, manufacturer, model, serialnumber, categoryPath, deviceType) {
var platform = this;
var uuid = UUIDGen.generate(identifier); // Changed from 'path' in 0.0.4
this.log(`Add Accessory: ${accessoryName}, ${path}, ${deviceType}`);
var newAccessory = new Accessory(accessoryName, uuid);
// Plugin can save context on accessory to help restore accessory in configureAccessory()
newAccessory.context.identifier = identifier
newAccessory.context.path = path
newAccessory.context.categoryPath = categoryPath
newAccessory.context.deviceType = deviceType
newAccessory.context.manufacturer = manufacturer
newAccessory.context.model = model // Tank Warning relies on model as tank type
newAccessory.context.serialnumber = serialnumber
newAccessory.context.subscriptions = []
// Add Device Information
newAccessory.getService(Service.AccessoryInformation)
.setCharacteristic(Characteristic.Manufacturer, manufacturer)
.setCharacteristic(Characteristic.Model, model)
.setCharacteristic(Characteristic.SerialNumber, serialnumber);
// Add Device Services
switch(deviceType) {
case 'switch':
newAccessory.addService(Service.Switch, accessoryName)
this.addSwitchServices(newAccessory);
break;
case 'dimmer':
newAccessory.addService(Service.Lightbulb, accessoryName)
this.addDimmerServices(newAccessory);
break;
case 'temperature':
newAccessory.addService(Service.TemperatureSensor, accessoryName)
this.addTemperatureServices(newAccessory);
break;
case 'humidity':
newAccessory.addService(Service.HumiditySensor, accessoryName)
this.addHumidityServices(newAccessory);
break;
case 'tank':
// newAccessory.addService(Service.LeakSensor, accessoryName)
newAccessory.addService(Service.HumiditySensor, accessoryName) // Workaround to shoe tank level
newAccessory.addService(Service.BatteryService, accessoryName) // Used for low tank level warning
this.addTankServices(newAccessory);
break;
case 'battery':
newAccessory.addService(Service.HumiditySensor, accessoryName) // Used as main accessory
newAccessory.addService(Service.BatteryService, accessoryName)
this.addVoltageBatteryServices(newAccessory);
break;
case 'batterySOC':
newAccessory.addService(Service.HumiditySensor, accessoryName) // Used as main accessory
newAccessory.addService(Service.BatteryService, accessoryName)
this.addSOCBatteryServices(newAccessory);
break;
case 'leakSensor':
newAccessory.addService(Service.LeakSensor, accessoryName)
this.addLeakServices(newAccessory);
break;
}
this.accessories.set(path, newAccessory);
// console.log(newAccessory);
this.api.registerPlatformAccessories("homebridge-signalk", "SignalK", [newAccessory]);
}
// Add services for Dimmer to existing accessory object
SignalKPlatform.prototype.addDimmerServices = function(accessory) {
var platform = this;
accessory.on('identify', function(paired, callback) {
platform.log(`Identifying Dimmer Accessory ${accessory.displayName} by off/on/off cycle`);
// FIXME: Get state of device before cycle
// var stateBefore;
// platform.getOnOff.bind(platform, path + '.state',(error,value)=> {stateBefore = value});
// console.log(stateBefore);
// Off/On/Off/Restore cycle
platform.setOnOff(accessory.context.identifier, false, errorHandler);
setTimeout(()=>{platform.setOnOff(accessory.context.identifier, true, errorHandler)
}, 250);
setTimeout(()=>{platform.setOnOff(accessory.context.identifier, false, errorHandler)
}, 750);
// FIXME: Restore original state of device before cycle
// setTimeout(()=>{platform.setOnOff(identifier, stateBefore)}, 1000);
callback();
});
// Make sure you provided a name for service, otherwise it may not visible in some HomeKit apps
var dataPath = accessory.context.path + '.state'
var subscriptionList = [];
accessory.getService(Service.Lightbulb)
.getCharacteristic(Characteristic.On)
.on('get', this.getOnOff.bind(this, dataPath))
.on('set', function(value, callback) {
platform.log(`Set dimmer ${accessory.displayName}.state to ${value}`)
platform.setOnOff(accessory.context.identifier, value, errorHandler)
callback();
})
subscription = new Object ();
subscription.characteristic = accessory.getService(Service.Lightbulb).getCharacteristic(Characteristic.On)
subscription.conversion = (body) => body == true
subscriptionList.push(subscription)
this.updateSubscriptions.set(dataPath, subscriptionList);
if (this.wsInitiated) {
this.ws.send(`{"context": "vessels.self","subscribe":[{"path":"${dataPath}"}]}`)
accessory.context.subscriptions.push(dataPath) // Link from accessory to subscription
};
dataPath = accessory.context.path + '.dimmingLevel'
subscriptionList = [];
accessory.getService(Service.Lightbulb)
.getCharacteristic(Characteristic.Brightness)
.on('get', this.getRatio.bind(this, dataPath))
.on('set', function(value, callback) {
platform.log(`Set dimmer ${accessory.displayName}.dimmingLevel to ${value}%`)
platform.SetRatio(accessory.context.identifier, value, errorHandler)
callback();
});
subscription = new Object ();
subscription.characteristic = accessory.getService(Service.Lightbulb).getCharacteristic(Characteristic.Brightness)
subscription.conversion = (body) => Number(body) * 100
subscriptionList.push(subscription)
this.updateSubscriptions.set(dataPath, subscriptionList);
if (this.wsInitiated) {
this.ws.send(`{"context": "vessels.self","subscribe":[{"path":"${dataPath}"}]}`)
accessory.context.subscriptions.push(dataPath) // Link from accessory to subscription
};
}
// Add services for Switch to existing accessory object
SignalKPlatform.prototype.addSwitchServices = function(accessory) {
var platform = this;
// Make sure you provided a name for service, otherwise it may not visible in some HomeKit apps
const dataPath = accessory.context.path + '.state'
var subscriptionList = [];
accessory.getService(Service.Switch)
.getCharacteristic(Characteristic.On)
.on('get', this.getOnOff.bind(this, dataPath))
.on('set', function(value, callback) {
platform.log(`Set switch ${accessory.displayName}.state to ${value}`)
platform.setOnOff(accessory.context.identifier, value, errorHandler)
callback();
});
subscription = new Object ();
subscription.characteristic = accessory.getService(Service.Switch).getCharacteristic(Characteristic.On)
subscription.conversion = (body) => body == true
subscriptionList.push(subscription)
this.updateSubscriptions.set(dataPath, subscriptionList);
if (this.wsInitiated) {
this.ws.send(`{"context": "vessels.self","subscribe":[{"path":"${dataPath}"}]}`)
accessory.context.subscriptions.push(dataPath) // Link from accessory to subscription
};
}
// Add services for Temperature Sensor to existing accessory object
SignalKPlatform.prototype.addTemperatureServices = function(accessory) {
// Make sure you provided a name for service, otherwise it may not visible in some HomeKit apps
var subscriptionList = [];
accessory.getService(Service.TemperatureSensor)
.getCharacteristic(Characteristic.CurrentTemperature)
.on('get', this.getTemperature.bind(this, accessory.context.path));
subscription = new Object ();
subscription.characteristic = accessory.getService(Service.TemperatureSensor).getCharacteristic(Characteristic.CurrentTemperature)
subscription.conversion = (body) => Number(body) - 273.15
subscriptionList.push(subscription)
this.updateSubscriptions.set(accessory.context.path, subscriptionList);
if (this.wsInitiated) {
this.ws.send(`{"context": "vessels.self","subscribe":[{"path":"${accessory.context.path}"}]}`)
accessory.context.subscriptions.push(accessory.context.path) // Link from accessory to subscription
};
}
// Add services for Humidity Sensor to existing accessory object
SignalKPlatform.prototype.addHumidityServices = function(accessory) {
// Make sure you provided a name for service, otherwise it may not visible in some HomeKit apps
var subscriptionList = [];
accessory.getService(Service.HumiditySensor)
.getCharacteristic(Characteristic.CurrentRelativeHumidity)
.on('get', this.getRatio.bind(this, accessory.context.path));
subscription = new Object ();
subscription.characteristic = accessory.getService(Service.HumiditySensor).getCharacteristic(Characteristic.CurrentRelativeHumidity)
subscription.conversion = (body) => Number(body) * 100
subscriptionList.push(subscription)
this.updateSubscriptions.set(accessory.context.path, subscriptionList);
if (this.wsInitiated) {
this.ws.send(`{"context": "vessels.self","subscribe":[{"path":"${accessory.context.path}"}]}`)
accessory.context.subscriptions.push(accessory.context.path) // Link from accessory to subscription
};
}
// Add services for Tanks (mapped as Humidity Sensor) to existing accessory object
SignalKPlatform.prototype.addTankServices = function(accessory) {
// Make sure you provided a name for service, otherwise it may not visible in some HomeKit apps
const dataPath = accessory.context.path + '.currentLevel'
var subscriptionList = [];
accessory.getService(Service.HumiditySensor) // Workaround, as Home app does not show tank levels
.getCharacteristic(Characteristic.CurrentRelativeHumidity)
.on('get', this.getRatio.bind(this, dataPath));
subscription = new Object ();
subscription.characteristic = accessory.getService(Service.HumiditySensor).getCharacteristic(Characteristic.CurrentRelativeHumidity)
subscription.conversion = (body) => Number(body) * 100
subscriptionList.push(subscription)
accessory.getService(Service.BatteryService)
.getCharacteristic(Characteristic.StatusLowBattery)
.on('get', this.getStatusLowTank.bind(this, dataPath, this.tankWarnCondition[accessory.context.model]));
subscription = new Object ();
subscription.characteristic = accessory.getService(Service.BatteryService).getCharacteristic(Characteristic.StatusLowBattery)
subscription.conversion = this.tankWarnCondition[accessory.context.model]
subscriptionList.push(subscription)
accessory.getService(Service.BatteryService)
.getCharacteristic(Characteristic.BatteryLevel)
.on('get', this.getRatio.bind(this, dataPath));
subscription = new Object ();
subscription.characteristic = accessory.getService(Service.BatteryService).getCharacteristic(Characteristic.BatteryLevel)
subscription.conversion = (body) => Number(body) * 100
subscriptionList.push(subscription)
this.updateSubscriptions.set(dataPath, subscriptionList);
if (this.wsInitiated) {
this.ws.send(`{"context": "vessels.self","subscribe":[{"path":"${dataPath}"}]}`)
accessory.context.subscriptions.push(dataPath) // Link from accessory to subscription
};
}
// Add services for Batteries (with Humidity Sensor as main accessory) to existing accessory object
SignalKPlatform.prototype.addVoltageBatteryServices = function(accessory) {
// Make sure you provided a name for service, otherwise it may not visible in some HomeKit apps
var dataPath = accessory.context.path + '.voltage'
var subscriptionList = [];
accessory.getService(Service.HumiditySensor) // Mapped to use humidity sensor to show SOC in Home app
.getCharacteristic(Characteristic.CurrentRelativeHumidity)
.on('get', this.getRatio.bind(this, dataPath));
subscription = new Object ();
subscription.characteristic = accessory.getService(Service.HumiditySensor).getCharacteristic(Characteristic.CurrentRelativeHumidity)
subscription.conversion = (voltage) => (Number(voltage) - this.emptyBatteryVoltage) / (this.fullBatteryVoltage - this.emptyBatteryVoltage) * 100
subscriptionList.push(subscription)
accessory.getService(Service.BatteryService)
.getCharacteristic(Characteristic.BatteryLevel)
.on('get', this.getRatio.bind(this, dataPath));
subscription = new Object ();
subscription.characteristic = accessory.getService(Service.BatteryService).getCharacteristic(Characteristic.BatteryLevel)
subscription.conversion = (voltage) => (Number(voltage) - this.emptyBatteryVoltage) / (this.fullBatteryVoltage - this.emptyBatteryVoltage) * 100
subscriptionList.push(subscription)
accessory.getService(Service.BatteryService)
.getCharacteristic(Characteristic.StatusLowBattery)
.on('get', this.getStatusWarnBattery.bind(this, dataPath, this.batteryWarnCondition.low));
subscription = new Object ();
subscription.characteristic = accessory.getService(Service.BatteryService).getCharacteristic(Characteristic.StatusLowBattery)
subscription.conversion = this.batteryWarnCondition.low
subscriptionList.push(subscription)
accessory.getService(Service.BatteryService)
.getCharacteristic(Characteristic.ChargingState)
.on('get', this.getStatusWarnBattery.bind(this, dataPath, this.batteryWarnCondition.charging));
subscription = new Object ();
subscription.characteristic = accessory.getService(Service.BatteryService).getCharacteristic(Characteristic.ChargingState)
subscription.conversion = this.batteryWarnCondition.charging
subscriptionList.push(subscription)
this.updateSubscriptions.set(dataPath, subscriptionList);
if (this.wsInitiated) {
this.ws.send(`{"context": "vessels.self","subscribe":[{"path":"${dataPath}"}]}`)
accessory.context.subscriptions.push(dataPath) // Link from accessory to subscription
};
// dataPath = accessory.context.path + '.chargingMode'
// accessory.getService(Service.BatteryService)
// .getCharacteristic(Characteristic.ChargingState)
// .on('get', this.getChargingState.bind(this, dataPath));
//
// subscriptionList = [];
// subscription = new Object ();
// subscription.characteristic = accessory.getService(Service.BatteryService).getCharacteristic(Characteristic.ChargingState)
// subscription.conversion = (body) => notChargingValues.indexOf(body) == -1 ? 1 : 0
// subscriptionList.push(subscription)
//
// this.updateSubscriptions.set(dataPath, subscriptionList);
// if (this.wsInitiated) {
// this.ws.send(`{"context": "vessels.self","subscribe":[{"path":"${dataPath}"}]}`)
// accessory.context.subscriptions.push(dataPath) // Link from accessory to subscription
// };
}
// Add services for SOC Batteries (with Humidity Sensor as main accessory) to existing accessory object
SignalKPlatform.prototype.addSOCBatteryServices = function(accessory) {
// Make sure you provided a name for service, otherwise it may not visible in some HomeKit apps
var dataPath = accessory.context.path + '.capacity.stateOfCharge'
var subscriptionList = [];
accessory.getService(Service.HumiditySensor) // Mapped to use humidity sensor to show SOC in Home app
.getCharacteristic(Characteristic.CurrentRelativeHumidity)
.on('get', this.getRatio.bind(this, dataPath));
subscription = new Object ();
subscription.characteristic = accessory.getService(Service.HumiditySensor).getCharacteristic(Characteristic.CurrentRelativeHumidity)
subscription.conversion = (body) => Number(body) * 100
subscriptionList.push(subscription)
accessory.getService(Service.BatteryService)
.getCharacteristic(Characteristic.BatteryLevel)
.on('get', this.getRatio.bind(this, dataPath));
subscription = new Object ();
subscription.characteristic = accessory.getService(Service.BatteryService).getCharacteristic(Characteristic.BatteryLevel)
subscription.conversion = (body) => Number(body) * 100
subscriptionList.push(subscription)
this.updateSubscriptions.set(dataPath, subscriptionList);
if (this.wsInitiated) {
this.ws.send(`{"context": "vessels.self","subscribe":[{"path":"${dataPath}"}]}`)
accessory.context.subscriptions.push(dataPath) // Link from accessory to subscription
};
// dataPath = accessory.context.path + '.chargingMode'
// accessory.getService(Service.BatteryService)
// .getCharacteristic(Characteristic.ChargingState)
// .on('get', this.getChargingState.bind(this, dataPath));
//
// subscriptionList = [];
// subscription = new Object ();
// subscription.characteristic = accessory.getService(Service.BatteryService).getCharacteristic(Characteristic.ChargingState)
// subscription.conversion = (body) => notChargingValues.indexOf(body) == -1 ? 1 : 0
// subscriptionList.push(subscription)
//
// this.updateSubscriptions.set(dataPath, subscriptionList);
// if (this.wsInitiated) {
// this.ws.send(`{"context": "vessels.self","subscribe":[{"path":"${dataPath}"}]}`)
// accessory.context.subscriptions.push(dataPath) // Link from accessory to subscription
// };
dataPath = accessory.context.path + '.voltage'
subscriptionList = [];
accessory.getService(Service.BatteryService)
.getCharacteristic(Characteristic.StatusLowBattery)
.on('get', this.getStatusWarnBattery.bind(this, dataPath, this.batteryWarnCondition.low));
subscription = new Object ();
subscription.characteristic = accessory.getService(Service.BatteryService).getCharacteristic(Characteristic.StatusLowBattery)
subscription.conversion = this.batteryWarnCondition.low
subscriptionList.push(subscription)
accessory.getService(Service.BatteryService)
.getCharacteristic(Characteristic.ChargingState)
.on('get', this.getStatusWarnBattery.bind(this, dataPath, this.batteryWarnCondition.charging));
subscription = new Object ();
subscription.characteristic = accessory.getService(Service.BatteryService).getCharacteristic(Characteristic.ChargingState)
subscription.conversion = this.batteryWarnCondition.charging
subscriptionList.push(subscription)
this.updateSubscriptions.set(dataPath, subscriptionList);
if (this.wsInitiated) {
this.ws.send(`{"context": "vessels.self","subscribe":[{"path":"${dataPath}"}]}`)
accessory.context.subscriptions.push(dataPath) // Link from accessory to subscription
};
}
// Add services for Leak Sensor to existing accessory object
SignalKPlatform.prototype.addLeakServices = function(accessory) {
// Make sure you provided a name for service, otherwise it may not visible in some HomeKit apps
const dataPath = accessory.context.path + '.state'
var subscriptionList = [];
accessory.getService(Service.LeakSensor)
.getCharacteristic(Characteristic.LeakDetected)
.on('get', this.getOnOff.bind(this, dataPath))
subscription = new Object ();
subscription.characteristic = accessory.getService(Service.LeakSensor).getCharacteristic(Characteristic.LeakDetected)
subscription.conversion = (body) => body == true
subscriptionList.push(subscription)
this.updateSubscriptions.set(dataPath, subscriptionList);
if (this.wsInitiated) {
this.ws.send(`{"context": "vessels.self","subscribe":[{"path":"${dataPath}"}]}`)
accessory.context.subscriptions.push(dataPath) // Link from accessory to subscription
};
}
SignalKPlatform.prototype.updateAccessoriesReachability = function() {
this.log("Update Reachability");
for (var accessory in this.accessories) {
accessory.updateReachability(false);
}
}
// Remove accessory
SignalKPlatform.prototype.removeAccessory = function(accessory) {
this.log('Remove accessory', accessory.displayName);
this.api.unregisterPlatformAccessories("homebridge-signalk", "SignalK", [accessory]);
this.accessories.delete(accessory.context.path);
this.updateSubscriptions.delete(accessory.context.path);
accessory.context.subscriptions.forEach(subscription => {
this.ws.send(`{"context": "vessels.self","unsubscribe":[{"path":"${subscription}"}]}`)
console.log('removed',`{"context": "vessels.self","unsubscribe":[{"path":"${subscription}"}]}`);
})
}
// - - - - - - - - - - - - - - - Signal K specific - - - - - - - - - - - - - -
// Autodetect Devices
// Autodetect from API all Dimmers, Switches
SignalKPlatform.prototype.autodetectNewAccessories = function() {
this.log("Autodecting " + this.url);
let headers = {}
if ( this.securityToken ) {
headers['Authorization'] = 'JWT ' + this.securityToken
}
request({url: this.url,
headers: headers},
(error, response, body) => {
if ( error ) {
this.log(`error: ${error}`);
} else if ( response.statusCode != 200 ) {
this.log(`error: response code ${response.statusCode}`)
} else {
this.processFullTree(body);
}
})
}
// Lookup full API Keys tree for HomeKit suitable devices
SignalKPlatform.prototype.processFullTree = function(body) {
var tree = JSON.parse(body);
// Add electrical controls: EmpirBus NXT and Venus GX
this.log("Adding electrical controls (EmpirBus NXT and Venus GX)");
var controls = _.get(tree, controlsPath);
if ( controls ) {
_.keys(controls).forEach(device => {
if (device.slice(0,empirBusIdentifier.length) == empirBusIdentifier
&& this.noignoredPath(`${controlsPath}.${device}`)
&& !this.accessories.has(`${controlsPath}.${device}`) ) {
httpLog(`Preparing EmpirBus NXT device: ${device} \n %O`, controls[device]);
var path = `${controlsPath}.${device}`;
var fallbackName = controls[device].meta.displayName ? controls[device].meta.displayName.value : controls[device].name.value;
var displayName = this.getName(path, fallbackName);
var deviceType = this.getDeviceType(`${controlsPath}.${device}`) || controls[device].type.value;
var manufacturer = controls[device].meta.manufacturer.name.value || "EmpirBus";
var model = controls[device].meta.manufacturer.model.value || "NXT DCM";
// addAccessory = function(accessoryName, identifier, path, manufacturer, model, serialnumber, categoryPath, deviceType)
httpLog(`Adding EmpirBus NXT device: \n accessoryName: ${displayName}, identifier: ${device}, path: ${path} \n manufacturer: ${manufacturer}, model: ${model}, serialnumber: ${controls[device].name.value} \n categoryPath: ${controlsPath}, deviceType: ${deviceType}`);
this.addAccessory(displayName, device, path, manufacturer, model, controls[device].name.value, controlsPath, deviceType);
} else
if (device.slice(0,venusRelaisIdentifier.length) == venusRelaisIdentifier
&& this.noignoredPath(`${controlsPath}.${device}`)
&& !this.accessories.has(`${controlsPath}.${device}`) ) {
httpLog(`Preparing Venus GX device: ${device} \n %O`, controls[device]);
var path = `${controlsPath}.${device}`;
var fallbackName = device; // FIXME: catch error in case of missing Metadata: controls[device].meta.displayName ? (controls[device].meta.displayName.value ? controls[device].meta.displayName.value : controls[device].meta.displayName) : controls[device].name.value;
var displayName = this.getName(path, fallbackName);
var deviceType = "switch";
var manufacturer = "Victron Energy"; // FIXME: catch error in case of missing Metadata: _.get(controls[device], "meta.manufacturer.name.value") || "Victron Energy";
var model = "Venus GX"; // FIXME: catch error in case of missing Metadata: _.get(controls[device], "meta.manufacturer.model.value") || "Venus GX";
if ( !fallbackName ) {
let parts = device.split('.')
fallbackName = parts[parts.length-1]
}
// addAccessory = function(accessoryName, identifier, path, manufacturer, model, serialnumber, categoryPath, deviceType)
httpLog(`Adding Venus GX device: \n accessoryName: ${displayName}, identifier: ${device}, path: ${path} \n manufacturer: ${manufacturer}, model: ${model}, serialnumber: ${device} \n categoryPath: ${controlsPath}, deviceType: ${deviceType}`);
this.addAccessory(displayName, device, path, manufacturer, model, device, controlsPath, deviceType);
}
});
}
this.log('Done');
// Add environments
this.log("Adding environment temperature and humidity");
environments.forEach(device => {
var path = `${environmentPath}.${device.key}`;
var environment = _.get(tree, path);
if ( environment
&& this.noignoredPath(path)
&& !this.accessories.has(path) ) {
var displayName = this.getName(path, device.displayName);
var deviceType = device.deviceType;
var manufacturer = 'NMEA';
var model = `${device.displayName} Sensor`;
this.addAccessory(displayName, device.key, path, manufacturer, model, displayName, environmentPath, deviceType);
}
});
this.log('Done');
// Add tanks
this.log("Adding tanks");
var tanks = _.get(tree, tanksPath);
if ( tanks ) {
_.keys(tanks).forEach(tankType => {
_.keys(tanks[tankType]).forEach(instance => {
var path = `${tanksPath}.${tankType}.${instance}`;
if (this.noignoredPath(path)
&& !this.accessories.has(path) ) {
var displayName = _.get(instance, "meta.displayName") || this.getName(path, tankType);
var deviceType = 'tank';
var manufacturer = "NMEA";
var model = tankType;
var deviceKey = `${tankType}.${instance}`;
this.addAccessory(displayName, deviceKey, path, manufacturer, model, deviceKey, tanksPath, deviceType);
}
})
});
}
this.log('Done');
// Add batteries
this.log("Adding batteries");
var batteries = _.get(tree, batteriesPath);
if ( batteries ) {
_.keys(batteries).forEach(instance => {
var path = `${batteriesPath}.${instance}`;
if (this.noignoredPath(path)
&& !this.accessories.has(path) ) {
httpLog('Preparing battery device: \n %O', batteries[instance]);
var displayName = this.getName(path, `Battery ${instance}`);
var deviceType = batteries[instance].capacity ? 'batterySOC' : 'battery';
var manufacturer = "NMEA"; // FIXME: batteries[instance].manufacturer.name.value || "NMEA";
var model = batteries[instance].capacity ? 'Battery SOC' : 'Battery'; // FIXME: batteries[instance].manufacturer.model.value || "Battery";
var deviceKey = `batteries.${instance}`;
// addAccessory = function(accessoryName, identifier, path, manufacturer, model, serialnumber, categoryPath, deviceType)
httpLog(`Adding battery device: \n accessoryName: ${displayName}, identifier: ${deviceKey}, path: ${path} \n manufacturer: ${manufacturer}, model: ${model}, serialnumber: ${displayName} \n categoryPath: ${batteriesPath}, deviceType: ${deviceType}`);
this.addAccessory(displayName, deviceKey, path, manufacturer, model, displayName, batteriesPath, deviceType);
}
});
}
this.log('Done');
// // Add chargers
// this.log("Adding chargers");
// var chargers = _.get(tree, chargersPath);
// if ( chargers ) {
// _.keys(chargers).forEach(instance => {
// var chargerInstancePath = `${chargersPath}.${instance}`;
//
// chargersDevices.forEach(device => {
// var path = `${chargerInstancePath}.${device.key}`;
// var chargerDevice = _.get(tree, path);
// if ( chargerDevice
// && this.noignoredPath(path)
// && !this.accessories.has(path) ) {
//
// httpLog('Preparing charger device: \n %O', chargers[instance]);
// var displayName = this.getName(path, device.displayName);
// var deviceType = device.deviceType;
// var manufacturer = 'Victron';
// var model = device.displayName;
// var deviceKey = `chargers.${instance}.${deviceType}`;
//