homebridge-alexa 0.8.3-beta.0 → 0.8.3-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -8,7 +8,11 @@ All notable changes to this project will be documented in this file. This projec
8
8
 
9
9
  #### Bug Fix
10
10
 
11
- - Fix for Routines #761
11
+ - Fix for Routines not working #761
12
+
13
+ #### Changes
14
+
15
+ - Increased test case coverage
12
16
 
13
17
  ## 0.8.2 (2024-12-27)
14
18
 
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "homebridge-alexa",
3
- "version": "0.8.3-beta.0",
3
+ "version": "0.8.3-beta.2",
4
4
  "description": "Control your Homebridge devices with Amazon Alexa.",
5
5
  "main": "src/plugin.js",
6
6
  "scripts": {
7
- "test": "jest --forceExit --detectOpenHandles --verbose=true --silent ",
7
+ "test": "jest --forceExit --detectOpenHandles --verbose=true ",
8
8
  "api": "documentation build plugin.js lib/alexaActions.js lib/alexaLocal.js lib/alexaMessages.js lib/alexaTranslator.js -f md --config docs/documentation.yml > docs/API.md",
9
9
  "document": "./gh-md-toc --hide-footer README.md ;./gh-md-toc --hide-footer Troubleshooting.md ;./gh-md-toc --hide-footer Installation.md; rm README.md.orig.* README.md.toc.* Troubleshooting.md.orig.* Troubleshooting.md.toc.* Installation.md.orig.* Installation.md.toc.*",
10
10
  "watch": "nodemon",
@@ -4,6 +4,7 @@ var alexaMessages = require('./alexaMessages.js');
4
4
  var messages = require('./parse/messages');
5
5
  var debug = require('debug')('alexaActions');
6
6
  var alexaLocal = require('./alexaLocal.js');
7
+ const process = require('process');
7
8
 
8
9
  var homebridge;
9
10
  var hbDevices;
@@ -27,7 +28,8 @@ module.exports = {
27
28
  alexaInputController: alexaInputController,
28
29
  alexaRangeController: alexaRangeController,
29
30
  alexaModeController: alexaModeController,
30
- destroy: destroy
31
+ destroy: destroy,
32
+ setHomebridge: setHomebridge
31
33
  };
32
34
 
33
35
  function hapDiscovery(options) {
@@ -49,10 +51,16 @@ function hapDiscovery(options) {
49
51
  // debug("Event Relay - 1", homebridge);
50
52
  }
51
53
 
54
+ // Used for testing
55
+
52
56
  function destroy() {
53
57
  homebridge.destroy();
54
58
  }
55
59
 
60
+ function setHomebridge(hb) {
61
+ homebridge = hb;
62
+ }
63
+
56
64
  function registerEvents(message) {
57
65
  // debug("registerEvents", message);
58
66
 
@@ -95,7 +103,7 @@ function registerEvents(message) {
95
103
  function alexaDiscovery(message, callback) {
96
104
  // debug('alexaDiscovery', this);
97
105
  homebridge.HAPaccessories(function (endPoints) {
98
- debug("alexaDiscovery", this);
106
+ // debug("alexaDiscovery", this);
99
107
  var response;
100
108
 
101
109
  hbDevices = new Homebridges(endPoints, this);
@@ -373,12 +381,13 @@ function alexaPowerController(message, callback) {
373
381
  }
374
382
 
375
383
  function alexaModeController(message, callback) {
376
- var action = message.directive.header.name;
384
+ const action = message.directive.header.name;
385
+ var response;
377
386
  try {
378
387
  var haAction = JSON.parse(message.directive.endpoint.cookie[action]);
379
388
  } catch (e) {
380
389
  this.log("alexaModeController missing action", action, e.message, message.directive.endpoint.cookie);
381
- var response = alexaMessages.alexaResponse(message, "", e);
390
+ response = alexaMessages.alexaResponse(message, "", e);
382
391
  response.event.payload.type = "INVALID_VALUE"; // The directive contains a value that is not valid for the target endpoint. For example, an invalid heating mode, channel, or program value.
383
392
  callback(e, response);
384
393
  return;
@@ -394,7 +403,7 @@ function alexaModeController(message, callback) {
394
403
  default:
395
404
  this.log("alexaModeController missing mode", action, message.directive.payload.mode);
396
405
  var e = new Error("alexaModeController missing mode " + action + " " + message.directive.payload);
397
- var response = alexaMessages.alexaResponse(message, "", e);
406
+ response = alexaMessages.alexaResponse(message, "", e);
398
407
  response.event.payload.type = "INVALID_VALUE"; // The directive contains a value that is not valid for the target endpoint. For example, an invalid heating mode, channel, or program value.
399
408
  callback(e, response);
400
409
  return;
@@ -420,12 +429,13 @@ function alexaModeController(message, callback) {
420
429
  }
421
430
 
422
431
  function alexaLockController(message, callback) {
423
- var action = message.directive.header.name;
432
+ const action = message.directive.header.name;
433
+ var response;
424
434
  try {
425
435
  var haAction = JSON.parse(message.directive.endpoint.cookie[action]);
426
436
  } catch (e) {
427
437
  this.log("alexaLockController missing action", action, e.message, message.directive.endpoint.cookie);
428
- var response = alexaMessages.alexaResponse(message, "", e);
438
+ response = alexaMessages.alexaResponse(message, "", e);
429
439
  response.event.payload.type = "INVALID_VALUE"; // The directive contains a value that is not valid for the target endpoint. For example, an invalid heating mode, channel, or program value.
430
440
  callback(e, response);
431
441
  return;
@@ -483,7 +493,7 @@ function alexaChannelController(message, callback) {
483
493
  } else {
484
494
  var e = new Error("ERROR: alexaChannelController missing channel", message.directive.endpoint.payload);
485
495
  this.log(e.message);
486
- var response = alexaMessages.alexaResponse(message, "", e);
496
+ response = alexaMessages.alexaResponse(message, "", e);
487
497
  response.event.payload.type = "INVALID_DIRECTIVE"; // The directive contains a value that is not valid for the target endpoint. For example, an invalid heating mode, channel, or program value.
488
498
  callback(e, response);
489
499
  return;
@@ -492,7 +502,7 @@ function alexaChannelController(message, callback) {
492
502
  var haAction = JSON.parse(message.directive.endpoint.cookie[channel.toUpperCase()]);
493
503
  } catch (e) {
494
504
  this.log("alexaChannelController invalid station", channel, e.message, message.directive.endpoint.cookie);
495
- var response = alexaMessages.alexaResponse(message, "", e);
505
+ response = alexaMessages.alexaResponse(message, "", e);
496
506
  response.event.payload.type = "VALUE_OUT_OF_RANGE"; // The directive contains a value that is not valid for the target endpoint. For example, an invalid heating mode, channel, or program value.
497
507
  callback(e, response);
498
508
  return;
@@ -510,11 +520,11 @@ function alexaChannelController(message, callback) {
510
520
 
511
521
  homebridge.HAPcontrolByDeviceID(haAction.deviceID, JSON.stringify(body), function (err, status) {
512
522
  if (err) {
513
- this.log.error(message.directive.header.namespace, action, haAction.deviceID, message.directive.endpoint.endpointId, (status ? status : ""), (err ? "ERROR: " + err : ""));
523
+ this.log.error(message.directive.header.namespace, haAction.deviceID, message.directive.endpoint.endpointId, (status ? status : ""), (err ? "ERROR: " + err : ""));
514
524
  } else if (status) {
515
- this.log.warn(message.directive.header.namespace, action, haAction.deviceID, message.directive.endpoint.endpointId, (status ? status : ""));
525
+ this.log.warn(message.directive.header.namespace, haAction.deviceID, message.directive.endpoint.endpointId, (status ? status : ""));
516
526
  } else {
517
- this.log(message.directive.header.namespace, action, haAction.deviceID, message.directive.endpoint.endpointId, (status ? status : ""));
527
+ this.log(message.directive.header.namespace, haAction.deviceID, message.directive.endpoint.endpointId, (status ? status : ""));
518
528
  }
519
529
  var response = alexaMessages.alexaResponse(message, status, err);
520
530
  callback(err, response);
@@ -523,14 +533,15 @@ function alexaChannelController(message, callback) {
523
533
 
524
534
  async function alexaThermostatController(message, callback) {
525
535
  // debug("alexaThermostatController", JSON.stringify(message));
526
- var action = message.directive.header.name;
527
- var payloads = message.directive.payload;
536
+ const action = message.directive.header.name;
537
+ const payloads = message.directive.payload;
538
+ var haAction;
528
539
  // directive.header.name = SetThermostatMode, SetTargetTemperature
529
540
  switch (action) {
530
541
  case "SetThermostatMode":
531
542
  try {
532
543
  var mode = message.directive.payload.thermostatMode.value;
533
- var haAction = JSON.parse(message.directive.endpoint.cookie["thermostatMode" + mode]);
544
+ haAction = JSON.parse(message.directive.endpoint.cookie["thermostatMode" + mode]);
534
545
  } catch (e) {
535
546
  this.log("alexaThermostatController missing action", "thermostatMode" + mode, e.message, message.directive.endpoint.cookie);
536
547
  var response = alexaMessages.alexaResponse(message, "", e);
@@ -554,7 +565,6 @@ async function alexaThermostatController(message, callback) {
554
565
  case "SetTargetTemperature":
555
566
  // targetSetpoint, lowerSetpoint, upperSetpoint
556
567
  var characteristics = [];
557
- var haAction;
558
568
  for (var index in payloads) {
559
569
  try {
560
570
  if (message.directive.endpoint.cookie[index]) {
@@ -1046,11 +1056,15 @@ async function processStatusArray(statusArray, message) {
1046
1056
  // debug("processStatusArray", messageArray);
1047
1057
  var resultArray = await Promise.all(messageArray);
1048
1058
 
1049
- // debug("processStatusArray-2", JSON.stringify(resultArray));
1050
- return (alexaMessages.alexaStateResponse(resultArray, message));
1059
+ if (resultArray[0].length === 0) {
1060
+ throw new Error('No response from Homebridge')
1061
+ } else {
1062
+ return (alexaMessages.alexaStateResponse(resultArray, message));
1063
+ }
1051
1064
  } catch (err) {
1065
+ debug("processStatusArray-Error", err);
1052
1066
  if (this.deviceCleanup) {
1053
- reportDeviceError(message);
1067
+ reportDeviceError.call(this, message);
1054
1068
  }
1055
1069
  return (alexaMessages.alexaStateResponse(err, message));
1056
1070
  }
@@ -1115,27 +1129,33 @@ function alexaEvent(events) {
1115
1129
  }
1116
1130
 
1117
1131
  function reportDeviceError(message) {
1118
- alexaLocal.alexaEvent({
1119
- "event": {
1120
- "header": {
1121
- "namespace": "Alexa.Discovery",
1122
- "name": "DeleteReport",
1123
- "messageId": messages.createMessageId(),
1124
- "payloadVersion": "3"
1125
- },
1126
- "payload": {
1127
- "endpoints": [
1128
- {
1129
- "endpointId": message.directive.endpoint.endpointId,
1132
+ // debug("reportDeviceError", message);
1133
+ this.log.error("Error: Device not responding, sending delete report", message.directive.endpoint.endpointId);
1134
+ try {
1135
+ alexaLocal.alexaEvent({
1136
+ "event": {
1137
+ "header": {
1138
+ "namespace": "Alexa.Discovery",
1139
+ "name": "DeleteReport",
1140
+ "messageId": messages.createMessageId(),
1141
+ "payloadVersion": "3"
1142
+ },
1143
+ "payload": {
1144
+ "endpoints": [
1145
+ {
1146
+ "endpointId": message.directive.endpoint.endpointId,
1147
+ }
1148
+ ],
1149
+ "scope": {
1150
+ "type": "BearerToken",
1151
+ "token": "OAuth2.0 bearer token"
1130
1152
  }
1131
- ],
1132
- "scope": {
1133
- "type": "BearerToken",
1134
- "token": "OAuth2.0 bearer token"
1135
1153
  }
1136
1154
  }
1137
- }
1138
- });
1155
+ });
1156
+ } catch (e) {
1157
+ debug("reportDeviceError:", e);
1158
+ }
1139
1159
  };
1140
1160
 
1141
1161
  /*
@@ -0,0 +1,205 @@
1
+ const { alexaMessage, setHomebridge, destroy } = require('./alexaActions.js');
2
+
3
+ jest.mock("hap-node-client", () => {
4
+ // console.log('Mock - hap-node-client');
5
+ return { HAPNodeJSClient: jest.fn() };
6
+ });
7
+
8
+ const HAPstatusByDeviceID = (deviceID, body, callback) => {
9
+ // console.log('Mock - HAPstatusByDeviceID', deviceID, body, callback);
10
+ switch (deviceID) {
11
+ case "ColorController-1":
12
+ callback(null, { deviceID: "device123", status: "on" });
13
+ break;
14
+ case "TemperatureSensor-Ok":
15
+ callback(null, { "characteristics": [{ "aid": 52, "iid": 12, "value": 2.5 }] });
16
+ break;
17
+ case "TemperatureSensor-NoData":
18
+ callback(null, { "characteristics": [{ "aid": 52, "iid": 12, "status": -70410 }] });
19
+ break;
20
+ default:
21
+ console.log('Missing Mock - HAPstatusByDeviceID', deviceID, body, callback);
22
+ callback(null, { deviceID: "device123", status: "off" });
23
+ }
24
+ }
25
+
26
+ setHomebridge({
27
+ HAPstatusByDeviceID: HAPstatusByDeviceID,
28
+ destroy: jest.fn()
29
+ });
30
+
31
+ describe('ReportState', () => {
32
+
33
+ const callback = jest.fn();
34
+
35
+ describe('deviceCleanup: false', () => {
36
+ const context = {
37
+ deviceCleanup: false,
38
+ log: jest.fn()
39
+ };
40
+ context.log.error = jest.fn();
41
+
42
+ beforeEach(() => {
43
+ callback.mockClear();
44
+ context.log.mockClear();
45
+ });
46
+
47
+ test('ReportState - ColorController', async () => {
48
+
49
+ alexaMessage.call(context, message1, callback);
50
+
51
+ await sleep(500);
52
+ // Add your assertions here to verify the behavior of the function
53
+ expect(callback).toHaveBeenCalled();
54
+ // expect(callback.mock.calls[0][0].context.properties[0].value).toBe(2.5);
55
+ // ...
56
+ }, 5000);
57
+
58
+ test('ReportState - TemperatureSensor - Ok', async () => {
59
+
60
+ alexaMessage.call(context, message2, callback);
61
+
62
+ await sleep(500);
63
+ // Add your assertions here to verify the behavior of the function
64
+ // console.log(JSON.stringify(callback.mock.calls[0][1], null, 2));
65
+ expect(callback).toHaveBeenCalled();
66
+ const response = callback.mock.calls[0][1];
67
+ expect(response.context.properties[0].value.value).toBe(2.5);
68
+ expect(response.context.properties[0].value.scale).toBe("CELSIUS");
69
+ // ...
70
+ }, 5000);
71
+
72
+ test('ReportState - TemperatureSensor - No Data', async () => {
73
+
74
+
75
+ alexaMessage.call(context, message3, callback);
76
+
77
+ await sleep(500);
78
+ // Add your assertions here to verify the behavior of the function
79
+ // console.log(JSON.stringify(callback.mock.calls[0][1], null, 2));
80
+ expect(callback).toHaveBeenCalled();
81
+ const response = callback.mock.calls[0][1];
82
+ expect(response.event.header.name).toBe('ErrorResponse');
83
+ expect(response.event.payload.type).toBe('ENDPOINT_UNREACHABLE');
84
+ // ...
85
+ }, 5000);
86
+
87
+
88
+ test('should handle unknown directive', () => {
89
+ alexaMessage.call(context, message4, callback);
90
+
91
+ // Add your assertions here to verify the behavior of the function
92
+ expect(callback).toHaveBeenCalled();
93
+ // ...
94
+ });
95
+ });
96
+
97
+ describe('deviceCleanup: true', () => {
98
+ var context = {
99
+ deviceCleanup: true,
100
+ log: jest.fn()
101
+ };
102
+
103
+ context.log.error = jest.fn();
104
+
105
+ beforeEach(() => {
106
+ callback.mockClear();
107
+ context.log.mockClear();
108
+ });
109
+
110
+ test('ReportState - ColorController', async () => {
111
+
112
+ alexaMessage.call(context, message1, callback);
113
+
114
+ await sleep(500);
115
+ // Add your assertions here to verify the behavior of the function
116
+ expect(callback).toHaveBeenCalled();
117
+ // expect(callback.mock.calls[0][0].context.properties[0].value).toBe(2.5);
118
+ // ...
119
+ }, 5000);
120
+
121
+ test('ReportState - TemperatureSensor - Ok', async () => {
122
+
123
+ alexaMessage.call(context, message2, callback);
124
+
125
+ await sleep(500);
126
+ // Add your assertions here to verify the behavior of the function
127
+ // console.log(JSON.stringify(callback.mock.calls[0][1], null, 2));
128
+ expect(callback).toHaveBeenCalled();
129
+ const response = callback.mock.calls[0][1];
130
+ expect(response.context.properties[0].value.value).toBe(2.5);
131
+ expect(response.context.properties[0].value.scale).toBe("CELSIUS");
132
+ expect(context.log).toHaveBeenCalledTimes(0);
133
+ expect(context.log.error).toHaveBeenCalledTimes(0);
134
+ // ...
135
+ }, 5000);
136
+
137
+ test('ReportState - TemperatureSensor - No Data', async () => {
138
+
139
+
140
+ alexaMessage.call(context, message3, callback);
141
+
142
+ await sleep(500);
143
+ // Add your assertions here to verify the behavior of the function
144
+ // console.log(JSON.stringify(callback.mock.calls[0][1], null, 2));
145
+ expect(callback).toHaveBeenCalled();
146
+ expect(context.log).toHaveBeenCalledTimes(0);
147
+ expect(context.log.error).toHaveBeenCalledTimes(1);
148
+ expect(context.log.error).toHaveBeenCalledWith("Error: Device not responding, sending delete report", "Njk6NjI6Qjc6QUU6Mzg6RDQtRGVmYXVsdCBNb2RlbC1OUkNIS0IgLSBMYUNyb3NzZS1UWDE0MVctQmFja3lhcmQtMDAwMDAwOEEtMDAwMC0xMDAwLTgwMDAtMDAyNkJCNzY1Mjkx");
149
+ const response = callback.mock.calls[0][1];
150
+ expect(response.event.header.name).toBe('ErrorResponse');
151
+ expect(response.event.payload.type).toBe('ENDPOINT_UNREACHABLE');
152
+ // ...
153
+ }, 5000);
154
+
155
+
156
+ test('should handle unknown directive', () => {
157
+ alexaMessage.call(context, message4, callback);
158
+
159
+ // Add your assertions here to verify the behavior of the function
160
+ expect(callback).toHaveBeenCalled();
161
+ // ...
162
+ });
163
+ });
164
+
165
+
166
+
167
+ afterAll(() => {
168
+ destroy();
169
+ });
170
+ });
171
+
172
+ async function sleep(ms) {
173
+ return new Promise(resolve => setTimeout(resolve, ms));
174
+ }
175
+
176
+
177
+ const message1 = {
178
+ directive: {
179
+ header: {
180
+ name: 'ReportState'
181
+ },
182
+ endpoint: {
183
+ cookie: {
184
+ ReportState: '[{"deviceID": "ColorController-1", "interface": "Alexa.ColorController", "hue": {"aid": "1", "iid": "1"}, "saturation": {"aid": "1", "iid": "2"}, "brightness": {"aid": "1", "iid": "3"}}]'
185
+ }
186
+ }
187
+ }
188
+ };
189
+
190
+ const message2 = { "directive": { "header": { "namespace": "Alexa", "name": "ReportState", "payloadVersion": "3", "messageId": "1cb7b217-3c2d-40e3-ab3d-fb66fb8bca2f", "correlationToken": "AAAAAAAAAAD9h7NYdun8GkFXkq4RJRZvAAIAAAAAAADHILDp6OTWHFoOX24pkmhvbtYnQ8g2cZAZwwHKZaR7/SF/tatX8I5tEBULWfoqY9WqeLu/WmF2n2mq4RFpbVg6yRZMPdeRbllXqMsG+tSGiiVmdyYT7BP32HlAELpOwtSXbnxNqGomxV7dqfZO2HYAj6qXSLUbnXYmSO7pDiMqT/PUbPSO+1MhcjYSF1UGV11JFihHGNuUyd0VN/bUoW46YWbxzB/zYPk+RUqA1uOfUzVWso8NuDNsE2BWFe4xO1thtJCOQjS9Wo5VA0avOeLO48aMNQ4Awby4aJWW+WzT+qp3v5xqQMwa3m0r8b89CTT2L4LcSD+A5JGE5nwppZyXjFeqgX5W1bY41z6cwjL6U+nW9xhQUzMXDDZ0/nD6bw77+oYQBkes2eexQbUgcl3cjw5OrmdbseOcyo4THzNRfuhZbebMQ/jTEameb/GnFWHoXdmpmR8Md5sEaDXv3X6Qfi2oCw7OXzuCBTHngGf82xw6wQd6ETymES0mZdsvwHTL3HUQBhR6xrAcg4MBPYuGSgVSiAAtresmexfxCDvYIcFf1o6c78w+o3c+w4Cprg6sU+OeF16ouuAjhs3qbX+sgmV9W9tWBPGirQA1WXvePz3LP8SPyjj0BAQ9nnr0tJ59jMtSaRwu6FFnwheVSAyZihggIVTD1pQ+nusFrJkahA==" }, "endpoint": { "endpointId": "Njk6NjI6Qjc6QUU6Mzg6RDQtRGVmYXVsdCBNb2RlbC1OUkNIS0IgLSBMYUNyb3NzZS1UWDE0MVctQmFja3lhcmQtMDAwMDAwOEEtMDAwMC0xMDAwLTgwMDAtMDAyNkJCNzY1Mjkx", "cookie": { "ReportState": "[{\"interface\":\"Alexa.TemperatureSensor\",\"deviceID\":\"TemperatureSensor-Ok\",\"aid\":52,\"iid\":12}]" } }, "payload": {} } };
191
+
192
+ const message3 = { "directive": { "header": { "namespace": "Alexa", "name": "ReportState", "payloadVersion": "3", "messageId": "1cb7b217-3c2d-40e3-ab3d-fb66fb8bca2f", "correlationToken": "AAAAAAAAAAD9h7NYdun8GkFXkq4RJRZvAAIAAAAAAADHILDp6OTWHFoOX24pkmhvbtYnQ8g2cZAZwwHKZaR7/SF/tatX8I5tEBULWfoqY9WqeLu/WmF2n2mq4RFpbVg6yRZMPdeRbllXqMsG+tSGiiVmdyYT7BP32HlAELpOwtSXbnxNqGomxV7dqfZO2HYAj6qXSLUbnXYmSO7pDiMqT/PUbPSO+1MhcjYSF1UGV11JFihHGNuUyd0VN/bUoW46YWbxzB/zYPk+RUqA1uOfUzVWso8NuDNsE2BWFe4xO1thtJCOQjS9Wo5VA0avOeLO48aMNQ4Awby4aJWW+WzT+qp3v5xqQMwa3m0r8b89CTT2L4LcSD+A5JGE5nwppZyXjFeqgX5W1bY41z6cwjL6U+nW9xhQUzMXDDZ0/nD6bw77+oYQBkes2eexQbUgcl3cjw5OrmdbseOcyo4THzNRfuhZbebMQ/jTEameb/GnFWHoXdmpmR8Md5sEaDXv3X6Qfi2oCw7OXzuCBTHngGf82xw6wQd6ETymES0mZdsvwHTL3HUQBhR6xrAcg4MBPYuGSgVSiAAtresmexfxCDvYIcFf1o6c78w+o3c+w4Cprg6sU+OeF16ouuAjhs3qbX+sgmV9W9tWBPGirQA1WXvePz3LP8SPyjj0BAQ9nnr0tJ59jMtSaRwu6FFnwheVSAyZihggIVTD1pQ+nusFrJkahA==" }, "endpoint": { "endpointId": "Njk6NjI6Qjc6QUU6Mzg6RDQtRGVmYXVsdCBNb2RlbC1OUkNIS0IgLSBMYUNyb3NzZS1UWDE0MVctQmFja3lhcmQtMDAwMDAwOEEtMDAwMC0xMDAwLTgwMDAtMDAyNkJCNzY1Mjkx", "cookie": { "ReportState": "[{\"interface\":\"Alexa.TemperatureSensor\",\"deviceID\":\"TemperatureSensor-NoData\",\"aid\":52,\"iid\":12}]" } }, "payload": {} } };
193
+
194
+ const message4 = {
195
+ directive: {
196
+ header: {
197
+ name: 'Unknown'
198
+ },
199
+ endpoint: {
200
+ cookie: {
201
+ reportstate: '[{"deviceID": "1", "interface": "Alexa.ColorController", "hue": {"aid": "1", "iid": "1"}, "saturation": {"aid": "1", "iid": "2"}, "brightness": {"aid": "1", "iid": "3"}}]'
202
+ }
203
+ }
204
+ }
205
+ };
@@ -1,5 +1,6 @@
1
1
  "use strict";
2
2
 
3
+ const process = require('process');
3
4
  const mqtt = require('mqtt');
4
5
  const debug = require('debug')('alexaLocal');
5
6
  const Bottleneck = require('bottleneck');
@@ -18,7 +19,7 @@ let Characteristic;
18
19
  module.exports = {
19
20
  alexaLocal,
20
21
  alexaEvent,
21
- alexaPriorityEvent,
22
+ alexaPriorityEvent
22
23
  };
23
24
 
24
25
  function alexaLocal(options) {
@@ -1,13 +1,11 @@
1
1
  const mqtt = require('mqtt');
2
- const debug = require('debug');
3
2
  const Bottleneck = require('bottleneck');
4
- const { alexaLocal, alexaEvent, alexaPriorityEvent } = require('/Users/sgracey/Code/homebridge-alexa/src/lib/alexaLocal');
3
+ const { alexaLocal, alexaEvent, alexaPriorityEvent } = require('./alexaLocal');
5
4
 
6
5
  jest.mock('mqtt');
7
- jest.mock('debug');
8
6
  jest.mock('bottleneck');
9
7
 
10
- describe.skip('alexaLocal', () => {
8
+ describe('alexaLocal', () => {
11
9
  let options;
12
10
  let mockClient;
13
11
  let mockLimiter;
@@ -32,6 +30,8 @@ describe.skip('alexaLocal', () => {
32
30
  log: jest.fn()
33
31
  };
34
32
 
33
+ options.log.error = jest.fn();
34
+
35
35
  mockClient = {
36
36
  on: jest.fn(),
37
37
  publish: jest.fn(),
@@ -110,7 +110,7 @@ describe.skip('alexaLocal', () => {
110
110
  options.Characteristic.ContactSensorState,
111
111
  options.Characteristic.ContactSensorState.CONTACT_NOT_DETECTED
112
112
  );
113
- expect(options.log.error).toHaveBeenCalledWith(expect.stringContaining('Login to homebridge.ca failed'));
113
+ expect(options.log.error).toHaveBeenCalledWith(expect.stringContaining('ERROR: (homebridge-alexa) Login failed. Validate credentials in config.json.'));
114
114
  });
115
115
 
116
116
  test('should publish alexaEvent', () => {
@@ -131,30 +131,79 @@ describe.skip('alexaLocal', () => {
131
131
  expect(mockLimiter.submit).toHaveBeenCalledWith({ priority: 4 }, expect.any(Function));
132
132
  });
133
133
 
134
- test('should generate alexaErrorResponse', () => {
135
- const message = {
136
- directive: {
137
- header: {
138
- messageId: 'testMessageId'
139
- }
140
- }
141
- };
134
+ describe('MQTT Message Handler', () => {
135
+ test("Without Response - should generate alexaErrorResponse", async () => {
136
+ alexaLocal(options);
137
+ const connectHandler = mockClient.on.mock.calls[0][1];
138
+ connectHandler();
139
+ mockClient.publish.mockClear();
140
+ // await sleep(10000);
141
+ // Find the message handler from mockClient.on calls
142
+ const messageHandler = mockClient.on.mock.calls.find(
143
+ (call) => call[0] === "message"
144
+ )[1];
145
+
146
+ // Simulate an incoming MQTT message
147
+ const topic = "command/testUser/1";
148
+ const payload = JSON.stringify(message1);
149
+
150
+ messageHandler(topic, payload);
151
+
152
+ // Verify eventBus.emit was called with the received message
153
+ expect(options.eventBus.emit).toHaveBeenCalledWith("Alexa", message1, expect.any(Function));
154
+
155
+ const emitCallback = options.eventBus.emit.mock.calls.find(
156
+ (call) => call[0] === "Alexa"
157
+ )[2];
158
+
159
+ expect(emitCallback).toBeInstanceOf(Function); // Ensure it's a function
160
+
161
+ // Call the captured callback
162
+ emitCallback();
163
+
164
+ expect(mockClient.publish).toHaveBeenCalledWith("response/testUser/1", "{\"event\":{\"header\":{\"name\":\"ErrorResponse\",\"namespace\":\"Alexa\",\"payloadVersion\":\"3\",\"messageId\":\"1cb7b217-3c2d-40e3-ab3d-fb66fb8bca2f\"},\"payload\":{\"type\":\"INVALID_DIRECTIVE\",\"message\":\"No listener for directive\"}}}");
165
+ expect(options.log.error).toHaveBeenCalledWith("ERROR Response", JSON.stringify(message1));
166
+ expect(options.log.error).toHaveBeenCalledTimes(1);
167
+ });
168
+
169
+ test("With Response", async () => {
170
+ alexaLocal(options);
171
+ const connectHandler = mockClient.on.mock.calls[0][1];
172
+ connectHandler();
173
+ mockClient.publish.mockClear();
174
+ // await sleep(10000);
175
+ // Find the message handler from mockClient.on calls
176
+ const messageHandler = mockClient.on.mock.calls.find(
177
+ (call) => call[0] === "message"
178
+ )[1];
179
+
180
+ // Simulate an incoming MQTT message
181
+ const topic = "command/testUser/1";
182
+ const payload = JSON.stringify(message1);
183
+
184
+ messageHandler(topic, payload);
185
+
186
+ // Verify eventBus.emit was called with the received message
187
+ expect(options.eventBus.emit).toHaveBeenCalledWith("Alexa", message1, expect.any(Function));
188
+
189
+ const emitCallback = options.eventBus.emit.mock.calls.find(
190
+ (call) => call[0] === "Alexa"
191
+ )[2];
192
+
193
+ expect(emitCallback).toBeInstanceOf(Function); // Ensure it's a function
194
+
195
+ // Call the captured callback
196
+ emitCallback(null, message1);
197
+
198
+ expect(mockClient.publish).toHaveBeenCalledWith('response/testUser/1', JSON.stringify(message1));
199
+ expect(options.log.error).toHaveBeenCalledTimes(0);
142
200
 
143
- const response = _alexaErrorResponse(message);
144
-
145
- expect(response).toEqual({
146
- event: {
147
- header: {
148
- name: 'ErrorResponse',
149
- namespace: 'Alexa',
150
- payloadVersion: '3',
151
- messageId: 'testMessageId'
152
- },
153
- payload: {
154
- type: 'INVALID_DIRECTIVE',
155
- message: 'No listener for directive'
156
- }
157
- }
158
201
  });
159
202
  });
160
- });
203
+ });
204
+
205
+ const message1 = { "directive": { "header": { "namespace": "Alexa", "name": "ReportState", "payloadVersion": "3", "messageId": "1cb7b217-3c2d-40e3-ab3d-fb66fb8bca2f", "correlationToken": "AAAAAAAAAAD9h7NYdun8GkFXkq4RJRZvAAIAAAAAAADHILDp6OTWHFoOX24pkmhvbtYnQ8g2cZAZwwHKZaR7/SF/tatX8I5tEBULWfoqY9WqeLu/WmF2n2mq4RFpbVg6yRZMPdeRbllXqMsG+tSGiiVmdyYT7BP32HlAELpOwtSXbnxNqGomxV7dqfZO2HYAj6qXSLUbnXYmSO7pDiMqT/PUbPSO+1MhcjYSF1UGV11JFihHGNuUyd0VN/bUoW46YWbxzB/zYPk+RUqA1uOfUzVWso8NuDNsE2BWFe4xO1thtJCOQjS9Wo5VA0avOeLO48aMNQ4Awby4aJWW+WzT+qp3v5xqQMwa3m0r8b89CTT2L4LcSD+A5JGE5nwppZyXjFeqgX5W1bY41z6cwjL6U+nW9xhQUzMXDDZ0/nD6bw77+oYQBkes2eexQbUgcl3cjw5OrmdbseOcyo4THzNRfuhZbebMQ/jTEameb/GnFWHoXdmpmR8Md5sEaDXv3X6Qfi2oCw7OXzuCBTHngGf82xw6wQd6ETymES0mZdsvwHTL3HUQBhR6xrAcg4MBPYuGSgVSiAAtresmexfxCDvYIcFf1o6c78w+o3c+w4Cprg6sU+OeF16ouuAjhs3qbX+sgmV9W9tWBPGirQA1WXvePz3LP8SPyjj0BAQ9nnr0tJ59jMtSaRwu6FFnwheVSAyZihggIVTD1pQ+nusFrJkahA==" }, "endpoint": { "endpointId": "Njk6NjI6Qjc6QUU6Mzg6RDQtRGVmYXVsdCBNb2RlbC1OUkNIS0IgLSBMYUNyb3NzZS1UWDE0MVctQmFja3lhcmQtMDAwMDAwOEEtMDAwMC0xMDAwLTgwMDAtMDAyNkJCNzY1Mjkx", "cookie": { "ReportState": "[{\"interface\":\"Alexa.TemperatureSensor\",\"deviceID\":\"TemperatureSensor-Ok\",\"aid\":52,\"iid\":12}]" } }, "payload": {} } };
206
+
207
+ async function sleep(ms) {
208
+ return new Promise((resolve) => setTimeout(resolve, ms));
209
+ }
@@ -467,12 +467,13 @@ function alexaResponse(message, hbResponse, err, value) {
467
467
  // alexaMessages.alexaStateResponse(message, reportState, status, err);
468
468
  // message, reportState, hbResponse, err
469
469
  function alexaStateResponse(properties, message) {
470
+ // debug("alexaStateResponse", properties, JSON.stringify(message, null, 2));
470
471
  var endpointId = message.directive.endpoint.endpointId;
471
472
  var messageId = message.directive.header.messageId;
472
473
  var correlationToken = message.directive.header.correlationToken;
473
474
  var response;
474
475
 
475
- if (properties instanceof Error) {
476
+ if (properties instanceof Error || properties[0].length === 0) {
476
477
  // console.log("ERROR: alexaStateResponse", properties.message);
477
478
  response = {
478
479
  "event": {
@@ -84,6 +84,24 @@ describe('alexaMessages', () => {
84
84
  expect(response.event.payload.type).toBe('ENDPOINT_UNREACHABLE');
85
85
  });
86
86
 
87
+ test('should return ErrorResponse when properties are empty', () => {
88
+ const properties = [[]];
89
+ const message = {
90
+ directive: {
91
+ header: {
92
+ messageId: '123',
93
+ name: 'ReportState'
94
+ },
95
+ endpoint: {
96
+ endpointId: 'endpoint-001'
97
+ }
98
+ }
99
+ };
100
+ const response = alexaStateResponse(properties, message);
101
+ expect(response.event.header.name).toBe('ErrorResponse');
102
+ expect(response.event.payload.type).toBe('ENDPOINT_UNREACHABLE');
103
+ });
104
+
87
105
  test('should return StateReport for ReportState directive', () => {
88
106
  const properties = [{
89
107
  namespace: 'Alexa.PowerController',
@@ -1,13 +1,64 @@
1
1
  var Homebridges = require('./Homebridges.js').Homebridges;
2
2
  const Homebridge = require('./Homebridge');
3
3
 
4
- describe('Homebridges', () => {
5
- test('should create an array of Homebridge instances', () => {
4
+ describe('Parse Discovery Response', () => {
6
5
 
7
- const fs = require('fs');
8
- const storagePath = 'test/endPoints.test.json';
9
- const devices = fs.readFileSync(storagePath);
6
+ test('Routines False', () => {
10
7
 
8
+ const devices = require('../../../test/endPoints.test.json');
9
+
10
+ const message = {};
11
+ const context = {
12
+ pin: '031-45-154',
13
+ filter: null,
14
+ beta: false,
15
+ routines: false,
16
+ combine: [
17
+ { into: 'Living', from: [Array] },
18
+ { into: 'Deck', from: [Array] }
19
+ ],
20
+ oldParser: false,
21
+ refresh: 900,
22
+ speakers: [
23
+ { manufacturer: 'yamaha-home', name: 'Deck' },
24
+ { manufacturer: 'yamaha-home', name: 'Living' },
25
+ { manufacturer: 'HTTP-IRBlaster', name: 'Stereo' }
26
+ ],
27
+ inputs: false,
28
+ channel: false,
29
+ blind: false,
30
+ thermostatTurnOn: 0,
31
+ deviceListHandling: 'none',
32
+ deviceList: [],
33
+ door: false,
34
+ name: 'Alexa',
35
+ mergeServiceName: false,
36
+ CloudTransport: 'wss',
37
+ LegacyCloudTransport: false,
38
+ keepalive: 300,
39
+ enhancedSkip: true,
40
+ deviceCleanup: true,
41
+ debug: true,
42
+ platform: 'Alexa'
43
+ };
44
+
45
+
46
+ const hbDevices = new Homebridges(devices, context);
47
+ expect(hbDevices.homebridges).toHaveLength(21);
48
+
49
+ const response = hbDevices.toAlexa(context, null);
50
+ expect(response.event.payload.endpoints).toHaveLength(87);
51
+
52
+ const discoveryResponse = require('../../../test/discoveryResponse.test.json');
53
+ expect(response).toEqual(discoveryResponse);
54
+
55
+ });
56
+
57
+ test('Routines True', () => {
58
+
59
+ const devices = require('../../../test/endPoints.test.json');
60
+
61
+ const message = {};
11
62
  const context = {
12
63
  pin: '031-45-154',
13
64
  filter: null,
@@ -42,13 +93,13 @@ describe('Homebridges', () => {
42
93
  platform: 'Alexa'
43
94
  };
44
95
 
45
- const homebridges = new Homebridges(JSON.parse(devices), context);
96
+ const hbDevices = new Homebridges(devices, context);
97
+ expect(hbDevices.homebridges).toHaveLength(21);
98
+
99
+ const response = hbDevices.toAlexa(context, null);
100
+ expect(response.event.payload.endpoints).toHaveLength(87);
46
101
 
47
- expect(homebridges.homebridges).toHaveLength(21);
48
- homebridges.homebridges.forEach((homebridge, index) => {
49
- expect(homebridge).toBeInstanceOf(Homebridge);
50
- expect(homebridge.element).toEqual(devices[index]);
51
- expect(homebridge.context).toBe(context);
52
- });
102
+ const discoveryResponse = require('../../../test/discoveryResponse.routines.test.json');
103
+ expect(response).toEqual(discoveryResponse);
53
104
  });
54
105
  });
@@ -54,192 +54,197 @@ function stateToProperties(statusObject, hbResponse) {
54
54
  // debug("stateToProperties - hbResponse", hbResponse);
55
55
  // Convert each individual HAP hbResponse to Alexa Format
56
56
  statusObject.elements.forEach((element, i) => {
57
- // debug("stateToProperties - element", element, i, hbResponse[i]);
58
-
59
- switch (element.interface.toLowerCase()) {
60
- case "alexa.speaker":
61
- properties.push({
62
- "namespace": "Alexa.Speaker",
63
- "name": "volume",
64
- "value": round(_getValue(element, hbResponse, i).value),
65
- "timeOfSample": now.toISOString(),
66
- "uncertaintyInMilliseconds": 500
67
- });
68
- properties.push({
69
- "namespace": "Alexa.Speaker",
70
- "name": "muted",
71
- "value": false,
72
- "timeOfSample": now.toISOString(),
73
- "uncertaintyInMilliseconds": 500
74
- });
75
- break;
76
- case "alexa.stepspeaker":
77
- // No response needed
78
- break;
79
- case "alexa.powercontroller":
80
- properties.push({
81
- "namespace": "Alexa.PowerController",
82
- "name": "powerState",
83
- "value": _getValue(element, hbResponse, i).value ? "ON" : "OFF",
84
- "timeOfSample": now.toISOString(),
85
- "uncertaintyInMilliseconds": 500
86
- });
87
- break;
88
- case "alexa.powerlevelcontroller":
89
- properties.push({
90
- "namespace": "Alexa.PowerLevelController",
91
- "name": "powerLevel",
92
- "value": round(_getValue(element, hbResponse, i).value),
93
- "timeOfSample": now.toISOString(),
94
- "uncertaintyInMilliseconds": 500
95
- });
96
- break;
97
- case "alexa.rangecontroller":
98
- properties.push({
99
- "namespace": "Alexa.RangeController",
100
- "name": "rangeValue",
101
- "value": round(_getValue(element, hbResponse, i).value),
102
- "timeOfSample": now.toISOString(),
103
- "uncertaintyInMilliseconds": 500
104
- });
105
- break;
106
- case "alexa.modecontroller":
107
- properties.push({
108
- "namespace": "Alexa.ModeController",
109
- "instance": "GarageDoor.Position",
110
- "name": "mode",
111
- "value": _getValue(element, hbResponse, i).value ? "Position.Down" : "Position.Up",
112
- "timeOfSample": now.toISOString(),
113
- "uncertaintyInMilliseconds": 500
114
- });
115
- break;
116
- case "alexa.colortemperaturecontroller":
117
- properties.push({
118
- "namespace": "Alexa.ColorTemperatureController",
119
- "name": "colorTemperatureInKelvin",
120
- "value": round(1000000 / _getValue(element, hbResponse, i).value),
121
- "timeOfSample": now.toISOString(),
122
- "uncertaintyInMilliseconds": 500
123
- });
124
- break;
125
- case "alexa.colorcontroller":
126
- properties.push({
127
- "namespace": "Alexa.ColorController",
128
- "name": "color",
129
- "value": _getValue(element, hbResponse, i).value,
130
- "timeOfSample": now.toISOString(),
131
- "uncertaintyInMilliseconds": 500
132
- });
133
- i = i + 2; // Skip over the 3 color values
134
- break;
135
- case "alexa.temperaturesensor":
136
- properties.push({
137
- "namespace": "Alexa.TemperatureSensor",
138
- "name": "temperature",
139
- "value": {
140
- "value": round(_getValue(element, hbResponse, i).value, 1),
141
- "scale": "CELSIUS"
142
- },
143
- "timeOfSample": now.toISOString(),
144
- "uncertaintyInMilliseconds": 500
145
- });
146
- break;
147
- case "alexa.contactsensor":
148
- properties.push({
149
- "namespace": "Alexa.ContactSensor",
150
- "name": "detectionState",
151
- "value": _getValue(element, hbResponse, i).value ? "DETECTED" : "NOT_DETECTED",
152
- "timeOfSample": now.toISOString(),
153
- "uncertaintyInMilliseconds": 500
154
- });
155
- break;
156
- case "alexa.motionsensor":
157
- properties.push({
158
- "namespace": "Alexa.MotionSensor",
159
- "name": "detectionState",
160
- "value": _getValue(element, hbResponse, i).value ? "DETECTED" : "NOT_DETECTED",
161
- "timeOfSample": now.toISOString(),
162
- "uncertaintyInMilliseconds": 500
163
- });
164
- break;
165
- case "alexa.doorbelleventsource":
166
- properties.push({
167
- "namespace": "Alexa.DoorbellEventSource",
168
- "name": "detectionState",
169
- "value": _getValue(element, hbResponse, i).value ? "DETECTED" : "NOT_DETECTED",
170
- "timeOfSample": now.toISOString(),
171
- "uncertaintyInMilliseconds": 500
172
- });
173
- break;
174
- // Characteristic.LockCurrentState.UNSECURED = 0;
175
- // Characteristic.LockCurrentState.SECURED = 1;
176
- // Characteristic.LockCurrentState.JAMMED = 2;
177
- // Characteristic.LockCurrentState.UNKNOWN = 3;
178
- case "alexa.lockcontroller":
179
- properties.push({
180
- "namespace": "Alexa.LockController",
181
- "name": "lockState",
182
- "value": _lockState(_getValue(element, hbResponse, i).value),
183
- "timeOfSample": now.toISOString(),
184
- "uncertaintyInMilliseconds": 500
185
- });
186
- break;
187
- case "alexa.thermostatcontrollertargetsetpoint":
188
- properties.push({
189
- namespace: "Alexa.ThermostatController",
190
- name: "targetSetpoint",
191
- value: {
192
- value: _getValue(element, hbResponse, i).value,
193
- scale: "CELSIUS"
194
- },
195
- timeOfSample: now.toISOString(),
196
- uncertaintyInMilliseconds: 500
197
- });
198
- break;
199
- case "alexa.thermostatcontrollerlowersetpoint":
200
- properties.push({
201
- "namespace": "Alexa.ThermostatController",
202
- "name": "lowerSetpoint",
203
- "value": {
204
- "value": _getValue(element, hbResponse, i).value,
205
- "scale": "CELSIUS"
206
- },
207
- "timeOfSample": now.toISOString(),
208
- "uncertaintyInMilliseconds": 500
209
- });
210
- break;
211
- case "alexa.thermostatcontrolleruppersetpoint":
212
- properties.push({
213
- "namespace": "Alexa.ThermostatController",
214
- "name": "upperSetpoint",
215
- "value": {
216
- "value": _getValue(element, hbResponse, i).value,
217
- "scale": "CELSIUS"
218
- },
219
- "timeOfSample": now.toISOString(),
220
- "uncertaintyInMilliseconds": 500
221
- });
222
- break;
223
- case "alexa.thermostatcontrollerthermostatmode":
224
- properties.push({
225
- "namespace": "Alexa.ThermostatController",
226
- "name": "thermostatMode",
227
- "value": _getThermoMode(_getValue(element, hbResponse, i).value),
228
- "timeOfSample": now.toISOString(),
229
- "uncertaintyInMilliseconds": 500
230
- });
231
- if (!statusObject.elements.find(x => x.interface.toLowerCase() === "alexa.powercontroller")) {
57
+ // debug("stateToProperties - element", element, _getValue(element, hbResponse, i).status);
58
+
59
+ if (_getValue(element, hbResponse, i).status === 0 || _getValue(element, hbResponse, i).status === undefined) {
60
+
61
+ switch (element.interface.toLowerCase()) {
62
+ case "alexa.speaker":
63
+ properties.push({
64
+ "namespace": "Alexa.Speaker",
65
+ "name": "volume",
66
+ "value": round(_getValue(element, hbResponse, i).value),
67
+ "timeOfSample": now.toISOString(),
68
+ "uncertaintyInMilliseconds": 500
69
+ });
70
+ properties.push({
71
+ "namespace": "Alexa.Speaker",
72
+ "name": "muted",
73
+ "value": false,
74
+ "timeOfSample": now.toISOString(),
75
+ "uncertaintyInMilliseconds": 500
76
+ });
77
+ break;
78
+ case "alexa.stepspeaker":
79
+ // No response needed
80
+ break;
81
+ case "alexa.powercontroller":
232
82
  properties.push({
233
83
  "namespace": "Alexa.PowerController",
234
84
  "name": "powerState",
235
- "value": properties[0].value === "OFF" ? "OFF" : "ON",
85
+ "value": _getValue(element, hbResponse, i).value ? "ON" : "OFF",
236
86
  "timeOfSample": now.toISOString(),
237
87
  "uncertaintyInMilliseconds": 500
238
88
  });
239
- }
240
- break;
241
- default:
242
- debug("ERROR: statusReport unknown/handled device", element, reportState);
89
+ break;
90
+ case "alexa.powerlevelcontroller":
91
+ properties.push({
92
+ "namespace": "Alexa.PowerLevelController",
93
+ "name": "powerLevel",
94
+ "value": round(_getValue(element, hbResponse, i).value),
95
+ "timeOfSample": now.toISOString(),
96
+ "uncertaintyInMilliseconds": 500
97
+ });
98
+ break;
99
+ case "alexa.rangecontroller":
100
+ properties.push({
101
+ "namespace": "Alexa.RangeController",
102
+ "name": "rangeValue",
103
+ "value": round(_getValue(element, hbResponse, i).value),
104
+ "timeOfSample": now.toISOString(),
105
+ "uncertaintyInMilliseconds": 500
106
+ });
107
+ break;
108
+ case "alexa.modecontroller":
109
+ properties.push({
110
+ "namespace": "Alexa.ModeController",
111
+ "instance": "GarageDoor.Position",
112
+ "name": "mode",
113
+ "value": _getValue(element, hbResponse, i).value ? "Position.Down" : "Position.Up",
114
+ "timeOfSample": now.toISOString(),
115
+ "uncertaintyInMilliseconds": 500
116
+ });
117
+ break;
118
+ case "alexa.colortemperaturecontroller":
119
+ properties.push({
120
+ "namespace": "Alexa.ColorTemperatureController",
121
+ "name": "colorTemperatureInKelvin",
122
+ "value": round(1000000 / _getValue(element, hbResponse, i).value),
123
+ "timeOfSample": now.toISOString(),
124
+ "uncertaintyInMilliseconds": 500
125
+ });
126
+ break;
127
+ case "alexa.colorcontroller":
128
+ properties.push({
129
+ "namespace": "Alexa.ColorController",
130
+ "name": "color",
131
+ "value": _getValue(element, hbResponse, i).value,
132
+ "timeOfSample": now.toISOString(),
133
+ "uncertaintyInMilliseconds": 500
134
+ });
135
+ i = i + 2; // Skip over the 3 color values
136
+ break;
137
+ case "alexa.temperaturesensor":
138
+ properties.push({
139
+ "namespace": "Alexa.TemperatureSensor",
140
+ "name": "temperature",
141
+ "value": {
142
+ "value": round(_getValue(element, hbResponse, i).value, 1),
143
+ "scale": "CELSIUS"
144
+ },
145
+ "timeOfSample": now.toISOString(),
146
+ "uncertaintyInMilliseconds": 500
147
+ });
148
+ break;
149
+ case "alexa.contactsensor":
150
+ properties.push({
151
+ "namespace": "Alexa.ContactSensor",
152
+ "name": "detectionState",
153
+ "value": _getValue(element, hbResponse, i).value ? "DETECTED" : "NOT_DETECTED",
154
+ "timeOfSample": now.toISOString(),
155
+ "uncertaintyInMilliseconds": 500
156
+ });
157
+ break;
158
+ case "alexa.motionsensor":
159
+ properties.push({
160
+ "namespace": "Alexa.MotionSensor",
161
+ "name": "detectionState",
162
+ "value": _getValue(element, hbResponse, i).value ? "DETECTED" : "NOT_DETECTED",
163
+ "timeOfSample": now.toISOString(),
164
+ "uncertaintyInMilliseconds": 500
165
+ });
166
+ break;
167
+ case "alexa.doorbelleventsource":
168
+ properties.push({
169
+ "namespace": "Alexa.DoorbellEventSource",
170
+ "name": "detectionState",
171
+ "value": _getValue(element, hbResponse, i).value ? "DETECTED" : "NOT_DETECTED",
172
+ "timeOfSample": now.toISOString(),
173
+ "uncertaintyInMilliseconds": 500
174
+ });
175
+ break;
176
+ // Characteristic.LockCurrentState.UNSECURED = 0;
177
+ // Characteristic.LockCurrentState.SECURED = 1;
178
+ // Characteristic.LockCurrentState.JAMMED = 2;
179
+ // Characteristic.LockCurrentState.UNKNOWN = 3;
180
+ case "alexa.lockcontroller":
181
+ properties.push({
182
+ "namespace": "Alexa.LockController",
183
+ "name": "lockState",
184
+ "value": _lockState(_getValue(element, hbResponse, i).value),
185
+ "timeOfSample": now.toISOString(),
186
+ "uncertaintyInMilliseconds": 500
187
+ });
188
+ break;
189
+ case "alexa.thermostatcontrollertargetsetpoint":
190
+ properties.push({
191
+ namespace: "Alexa.ThermostatController",
192
+ name: "targetSetpoint",
193
+ value: {
194
+ value: _getValue(element, hbResponse, i).value,
195
+ scale: "CELSIUS"
196
+ },
197
+ timeOfSample: now.toISOString(),
198
+ uncertaintyInMilliseconds: 500
199
+ });
200
+ break;
201
+ case "alexa.thermostatcontrollerlowersetpoint":
202
+ properties.push({
203
+ "namespace": "Alexa.ThermostatController",
204
+ "name": "lowerSetpoint",
205
+ "value": {
206
+ "value": _getValue(element, hbResponse, i).value,
207
+ "scale": "CELSIUS"
208
+ },
209
+ "timeOfSample": now.toISOString(),
210
+ "uncertaintyInMilliseconds": 500
211
+ });
212
+ break;
213
+ case "alexa.thermostatcontrolleruppersetpoint":
214
+ properties.push({
215
+ "namespace": "Alexa.ThermostatController",
216
+ "name": "upperSetpoint",
217
+ "value": {
218
+ "value": _getValue(element, hbResponse, i).value,
219
+ "scale": "CELSIUS"
220
+ },
221
+ "timeOfSample": now.toISOString(),
222
+ "uncertaintyInMilliseconds": 500
223
+ });
224
+ break;
225
+ case "alexa.thermostatcontrollerthermostatmode":
226
+ properties.push({
227
+ "namespace": "Alexa.ThermostatController",
228
+ "name": "thermostatMode",
229
+ "value": _getThermoMode(_getValue(element, hbResponse, i).value),
230
+ "timeOfSample": now.toISOString(),
231
+ "uncertaintyInMilliseconds": 500
232
+ });
233
+ if (!statusObject.elements.find(x => x.interface.toLowerCase() === "alexa.powercontroller")) {
234
+ properties.push({
235
+ "namespace": "Alexa.PowerController",
236
+ "name": "powerState",
237
+ "value": properties[0].value === "OFF" ? "OFF" : "ON",
238
+ "timeOfSample": now.toISOString(),
239
+ "uncertaintyInMilliseconds": 500
240
+ });
241
+ }
242
+ break;
243
+ default:
244
+ debug("ERROR: statusReport unknown/handled device", element, reportState);
245
+ }
246
+ } else {
247
+ debug("ERROR: statusReport error", element, _getValue(element, hbResponse, i));
243
248
  }
244
249
  });
245
250
 
@@ -1271,7 +1276,7 @@ function _getValue(element, hbResponse) {
1271
1276
  saturation: _round(_getHBValue(element.saturation, hbResponse).value / 100, 4),
1272
1277
  brightness: _round(_getHBValue(element.brightness, hbResponse).value / 100, 4)
1273
1278
  };
1274
- debug("Color Value", value);
1279
+ // debug("Color Value", value);
1275
1280
  return {
1276
1281
  value: value,
1277
1282
  status: 0
@@ -49,22 +49,13 @@ describe('stateToProperties', () => {
49
49
 
50
50
  test('should convert Alexa.TemperatureSensor error response correctly', () => {
51
51
  const statusObject = {
52
- elements: [{ interface: 'Alexa.TemperatureSensor', aid: 101, iid: 10 }]
52
+ elements: [{ interface: 'Alexa.TemperatureSensor', aid: 123, iid: 10 }]
53
53
  };
54
54
  const hbResponse = [{ aid: 123, iid: 10, status: -70410 }];
55
55
 
56
56
  const result = stateToProperties(statusObject, hbResponse);
57
57
 
58
- expect(result).toEqual([{
59
- namespace: 'Alexa.TemperatureSensor',
60
- name: 'temperature',
61
- value: {
62
- "scale": "CELSIUS",
63
- "value": NaN,
64
- },
65
- timeOfSample: mockDate,
66
- uncertaintyInMilliseconds: 500
67
- }]);
58
+ expect(result).toHaveLength(0);
68
59
  });
69
60
 
70
61
  test('should convert Alexa.ColorController response correctly', () => {
@@ -1,95 +0,0 @@
1
- const { processStatusArray } = require('/Users/sgracey/Code/homebridge-alexa/src/lib/alexaActions.js');
2
- const alexaMessages = require('/Users/sgracey/Code/homebridge-alexa/src/lib/alexaMessages.js');
3
- const homebridge = require('hap-node-client').HAPNodeJSClient;
4
-
5
- jest.mock('hap-node-client');
6
- jest.mock('/Users/sgracey/Code/homebridge-alexa/src/lib/alexaMessages.js');
7
-
8
- describe('processStatusArray', () => {
9
- let statusArray;
10
- let message;
11
-
12
- beforeEach(() => {
13
- statusArray = [
14
- {
15
- deviceID: 'device1',
16
- body: '?id=1.1',
17
- interface: 'Alexa.PowerController',
18
- spacer: ',',
19
- elements: [
20
- { interface: 'Alexa.PowerController', aid: 1, iid: 1 }
21
- ]
22
- },
23
- {
24
- deviceID: 'device2',
25
- body: '?id=2.1',
26
- interface: 'Alexa.BrightnessController',
27
- spacer: ',',
28
- elements: [
29
- { interface: 'Alexa.BrightnessController', aid: 2, iid: 1 }
30
- ]
31
- }
32
- ];
33
- message = { directive: { header: { messageId: '123' } } };
34
-
35
- homebridge.HAPstatusByDeviceID.mockImplementation((deviceID, body, callback) => {
36
- if (deviceID === 'device1') {
37
- callback(null, { characteristics: [{ aid: 1, iid: 1, value: true }] });
38
- } else if (deviceID === 'device2') {
39
- callback(null, { characteristics: [{ aid: 2, iid: 1, value: 50 }] });
40
- } else {
41
- callback(new Error('Device not found'));
42
- }
43
- });
44
-
45
- alexaMessages.alexaStateResponse.mockImplementation((resultArray, message) => {
46
- return { event: { header: { messageId: message.directive.header.messageId }, payload: { properties: resultArray } } };
47
- });
48
- });
49
-
50
- test.skip('should process status array successfully', async () => {
51
- const result = await processStatusArray(statusArray, message);
52
- expect(result).toEqual({
53
- event: {
54
- header: { messageId: '123' },
55
- payload: {
56
- properties: [
57
- { interface: 'Alexa.PowerController', aid: 1, iid: 1, value: true },
58
- { interface: 'Alexa.BrightnessController', aid: 2, iid: 1, value: 50 }
59
- ]
60
- }
61
- }
62
- });
63
- });
64
-
65
- test.skip('should handle errors during processing', async () => {
66
- homebridge.HAPstatusByDeviceID.mockImplementationOnce((deviceID, body, callback) => {
67
- callback(new Error('Device not found'));
68
- });
69
-
70
- const result = await processStatusArray(statusArray, message);
71
- expect(result).toEqual({
72
- event: {
73
- header: { messageId: '123' },
74
- payload: {
75
- properties: [
76
- { interface: 'Alexa.PowerController', aid: 1, iid: 1, value: true },
77
- { interface: 'Alexa.BrightnessController', aid: 2, iid: 1, value: 50 }
78
- ]
79
- }
80
- }
81
- });
82
- });
83
-
84
- test.skip('should return correct response format', async () => {
85
- const result = await processStatusArray(statusArray, message);
86
- expect(result).toHaveProperty('event.header.messageId', '123');
87
- expect(result).toHaveProperty('event.payload.properties');
88
- expect(result.event.payload.properties).toHaveLength(2);
89
- });
90
-
91
- afterAll(() => {
92
- jest.clearAllMocks();
93
- homebridge.destroy();
94
- });
95
- });