homebridge-alexa 0.6.9-beta.0 → 0.6.9-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/Installation.md CHANGED
@@ -26,6 +26,7 @@ Installation and Configuration of Homebridge Alexa
26
26
  * [keepalive - Cloud Server Connection Keepalive](#keepalive---cloud-server-connection-keepalive)
27
27
  * [refresh - Accessory Cache Refresh Interval](#refresh---accessory-cache-refresh-interval)
28
28
  * [filter - Homebridge Instance Filter](#filter---homebridge-instance-filter)
29
+ * [mergeServiceName - Alternate device naming](#mergeservicename---alternate-device-naming)
29
30
  * [blind](#blind)
30
31
  * [door](#door)
31
32
  * [Speaker Settings](#speaker-settings)
@@ -40,7 +41,7 @@ Installation and Configuration of Homebridge Alexa
40
41
  * [Discover Devices](#discover-devices)
41
42
 
42
43
  <!-- Created by https://github.com/ekalinin/github-markdown-toc -->
43
- <!-- Added by: sgracey, at: Tue 3 Jan 2023 10:41:47 EST -->
44
+ <!-- Added by: runner, at: Thu Nov 23 16:28:33 UTC 2023 -->
44
45
 
45
46
  <!--te-->
46
47
 
package/README.md CHANGED
@@ -37,10 +37,54 @@ Country availability - The plugin is available in these countries, English (AU),
37
37
 
38
38
  # Table of Contents
39
39
  <!--ts-->
40
-
40
+ * [Note to users of the service](#note-to-users-of-the-service)
41
+ * [New Users](#new-users)
42
+ * [Availability](#availability)
43
+ * [Features](#features)
44
+ * [Table of Contents](#table-of-contents)
45
+ * [Supported devices](#supported-devices)
46
+ * [HomeKit/Homebridge Devices supported](#homekithomebridge-devices-supported)
47
+ * [Native Support](#native-support)
48
+ * [Supported as Other Types](#supported-as-other-types)
49
+ * [Non-Homebridge Devices](#non-homebridge-devices)
50
+ * [Unsupported device types](#unsupported-device-types)
51
+ * [Alexa Voice Commands](#alexa-voice-commands)
52
+ * [Setup](#setup)
53
+ * [Light bulbs / Switches / Dimmer Switches](#light-bulbs--switches--dimmer-switches)
54
+ * [Color lights](#color-lights)
55
+ * [Color temperature](#color-temperature)
56
+ * [Color Temperatures](#color-temperatures)
57
+ * [Garage door, Blinds and Window Coverings](#garage-door-blinds-and-window-coverings)
58
+ * [Garage Door With door = false](#garage-door-with-door--false)
59
+ * [Window coverings / blinds With blind = false](#window-coverings--blinds-with-blind--false)
60
+ * [Garage Door With blind = true ( Not supported in all countries )](#garage-door-with-blind--true--not-supported-in-all-countries-)
61
+ * [Window coverings / blinds With blind = true ( Not supported in all countries )](#window-coverings--blinds-with-blind--true--not-supported-in-all-countries-)
62
+ * [Thermostat's and Heater / Cooler's](#thermostats-and-heater--coolers)
63
+ * [Lock / Unlock Doors](#lock--unlock-doors)
64
+ * [Temperature sensors](#temperature-sensors)
65
+ * [AppleTV ( homebridge-apple-tv or homebridge-apple-tv-remote )](#appletv--homebridge-apple-tv-or-homebridge-apple-tv-remote-)
66
+ * [HomeKit Television](#homekit-television)
67
+ * [HomeKit Television - Tested plugins](#homekit-television---tested-plugins)
68
+ * [Television Inputs and Channels](#television-inputs-and-channels)
69
+ * [Speakers](#speakers)
70
+ * [Bose SoundLink - Change preset](#bose-soundlink---change-preset)
71
+ * [Yamaha Receiver/Spotify control](#yamaha-receiverspotify-control)
72
+ * [Contact and Motion Sensors](#contact-and-motion-sensors)
73
+ * [Door bell devices](#door-bell-devices)
74
+ * [Installation of homebridge-alexa](#installation-of-homebridge-alexa)
75
+ * [Service Availability and Issues](#service-availability-and-issues)
76
+ * [Homebridge cloud service monitoring ( homebridge.ca )](#homebridge-cloud-service-monitoring--homebridgeca-)
77
+ * [Raising Issues and Troubleshooting](#raising-issues-and-troubleshooting)
78
+ * [Troubleshooting](#troubleshooting)
79
+ * [Known Issues](#known-issues)
80
+ * [Discord Channel](#discord-channel)
81
+ * [Debug logs](#debug-logs)
82
+ * [Homebridge Accessory Dump](#homebridge-accessory-dump)
83
+ * [Roadmap](#roadmap)
84
+ * [Credits](#credits)
41
85
 
42
86
  <!-- Created by https://github.com/ekalinin/github-markdown-toc -->
43
- <!-- Added by: sgracey, at: Wed 27 Sep 2023 19:52:24 EDT -->
87
+ <!-- Added by: runner, at: Thu Nov 23 16:28:32 UTC 2023 -->
44
88
 
45
89
  <!--te-->
46
90
 
@@ -1,10 +1,40 @@
1
1
  **Troubleshooting Tips**
2
2
 
3
3
  <!--ts-->
4
-
4
+ * [Initial Setup](#initial-setup)
5
+ * [[Alexa] ERROR: ( homebridge-alexa) Login to homebridge.ca failed, please validate your credentials in config.json and restart homebridge.](#alexa-error--homebridge-alexa-login-to-homebridgeca-failed-please-validate-your-credentials-in-configjson-and-restart-homebridge)
6
+ * [- Bad login or password in your config.json for <a href="https://www.homebridge.ca" rel="nofollow">https://www.homebridge.ca</a>](#--bad-login-or-password-in-your-configjson-for-httpswwwhomebridgeca)
7
+ * [[Alexa] ERROR: ( homebridge-alexa) You have an issue with your installation, please review the README.](#alexa-error--homebridge-alexa-you-have-an-issue-with-your-installation-please-review-the-readme)
8
+ * [- Cloud Server DDOS Protection has blocked your IP address](#--cloud-server-ddos-protection-has-blocked-your-ip-address)
9
+ * [- Multiple copies of homebridge-alexa on your network](#--multiple-copies-of-homebridge-alexa-on-your-network)
10
+ * [- VPN Software interfering with homebridge-alexa to homebridge.ca communications](#--vpn-software-interfering-with-homebridge-alexa-to-homebridgeca-communications)
11
+ * [[Alexa] ERROR: ( homebridge-alexa) Stopping Home Skill connection due to excessive reconnects, please review the README.](#alexa-error--homebridge-alexa-stopping-home-skill-connection-due-to-excessive-reconnects-please-review-the-readme)
12
+ * [[Alexa] WARNING: Duplicate device name xxxxx](#alexa-warning-duplicate-device-name-xxxxx)
13
+ * [Initial Setup Messages from DEBUG mode](#initial-setup-messages-from-debug-mode)
14
+ * [alexaHAP HAP Discover failed ... is not running in insecure mode](#alexahap-hap-discover-failed--is-not-running-in-insecure-mode)
15
+ * [HAP Discover failed ..... error code 470](#hap-discover-failed--error-code-470)
16
+ * [Upgraded from old version and am seeing this error message](#upgraded-from-old-version-and-am-seeing-this-error-message)
17
+ * [[Alexa] ERROR: HAP Discovery failed, please review config](#alexa-error-hap-discovery-failed-please-review-config)
18
+ * [alexaLocal ERROR: connect ECONNREFUSED 35.169.132.61:1883 -&gt; ECONNREFUSED](#alexalocal-error-connect-econnrefused-35169132611883----econnrefused)
19
+ * [alexaLocal error { Error: connect ECONNREFUSED 35.169.132.61:8883](#alexalocal-error--error-connect-econnrefused-35169132618883)
20
+ * [Device Discovery](#device-discovery)
21
+ * [Device discovery fails and the plugin logs show no issues.](#device-discovery-fails-and-the-plugin-logs-show-no-issues)
22
+ * [Device discovery fails, and this message is in the logs ERROR: Empty accessory name, parsing failed.](#device-discovery-fails-and-this-message-is-in-the-logs-error-empty-accessory-name-parsing-failed)
23
+ * [Device discovery fails, and this message is in the logs ERROR: Maximum devices/accessories of 300 exceeded.](#device-discovery-fails-and-this-message-is-in-the-logs-error-maximum-devicesaccessories-of-300-exceeded)
24
+ * [Device discovery fails, and this message is in the logs ERROR: Parsing failed, duplicate endpointID.](#device-discovery-fails-and-this-message-is-in-the-logs-error-parsing-failed-duplicate-endpointid)
25
+ * [After restarting homebridge Alexa can't find devices and needs to discover them again. Or you have duplicate devices in Alexa](#after-restarting-homebridge-alexa-cant-find-devices-and-needs-to-discover-them-again--or-you-have-duplicate-devices-in-alexa)
26
+ * [Controlling devices](#controlling-devices)
27
+ * [[Alexa] PowerController TurnOff 192.168.1.226 51826 undefined Error: Homebridge auth failed, invalid PIN](#alexa-powercontroller-turnoff-1921681226-51826-undefined-error-homebridge-auth-failed-invalid-pin)
28
+ * [Event error messages](#event-error-messages)
29
+ * [[Alexa] WARNING: ( homebridge-alexa) Dropped event message, message rate too high.](#alexa-warning--homebridge-alexa-dropped-event-message-message-rate-too-high)
30
+ * [ERROR: Error: getAccessToken No data Error: XXXXXXXXXX](#error--error-getaccesstoken-no-data-error-xxxxxxxxxx)
31
+ * [ERROR: Error: getAccessToken Token not found](#error--error-getaccesstoken-token-not-found)
32
+ * [Unsuccessful event message ( No event gateway token )](#unsuccessful-event-message--no-event-gateway-token-)
33
+ * [Successful event message being sent to Alexa](#successful-event-message-being-sent-to-alexa)
34
+ * [[Alexa] ERROR: Event gateway token refresh error: 400](#alexa-error--event-gateway-token-refresh-error-400)
5
35
 
6
36
  <!-- Created by https://github.com/ekalinin/github-markdown-toc -->
7
- <!-- Added by: sgracey, at: Wed 27 Sep 2023 19:52:25 EDT -->
37
+ <!-- Added by: runner, at: Thu Nov 23 16:28:33 UTC 2023 -->
8
38
 
9
39
  <!--te-->
10
40
 
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,43 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const server_helpers_for_client_tests_1 = require("./server_helpers_for_client_tests");
4
+ var AlexaLocal = require('./lib/alexaLocal.js').alexaLocal;
5
+ jest.setTimeout(30000);
6
+ describe('MQTT Client', () => {
7
+ beforeAll(async () => {
8
+ var version;
9
+ let client = null;
10
+ let publishCount = 0;
11
+ const server2 = (0, server_helpers_for_client_tests_1.default)('mqtt', (serverClient) => {
12
+ serverClient.on('connect', () => {
13
+ const connack = version === 5 ? { reasonCode: 0 } : { returnCode: 0 };
14
+ serverClient.connack(connack);
15
+ });
16
+ serverClient.on('publish', (packet) => {
17
+ console.log(packet.payload.toString());
18
+ if (packet.qos !== 0) {
19
+ serverClient.puback({ messageId: packet.messageId });
20
+ }
21
+ });
22
+ });
23
+ }, 300000);
24
+ afterAll(async () => {
25
+ });
26
+ describe('Validate Inital Startup', () => {
27
+ test('getconf GNU_LIBC_VERSION', async () => {
28
+ var options = {
29
+ mqttURL: 'mqtt://localhost:1883',
30
+ transport: 'mqtt',
31
+ mqttOptions: {
32
+ username: 'TEST',
33
+ password: 'PASSWORD',
34
+ reconnectPeriod: 33,
35
+ keepalive: 55,
36
+ rejectUnauthorized: false
37
+ },
38
+ };
39
+ var alexa = new AlexaLocal(options);
40
+ });
41
+ });
42
+ });
43
+ //# sourceMappingURL=client.test.js.map
@@ -0,0 +1 @@
1
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I,CAAC,0BAA0B,EAAE,KAAK,IAAI,EAAE;YAC1C,IAAI,OAAO,GAAG;gBAEZ,OAAO,EAAE,uBAAuB;gBAChC,SAAS,EAAE,MAAM;gBACjB,WAAW,EAAE;oBACX,QAAQ,EAAE,MAAM;oBAChB,QAAQ,EAAE,UAAU;oBACpB,eAAe,EAAE,EAAE;oBACnB,SAAS,EAAE,EAAE;oBACb,kBAAkB,EAAE,KAAK;iBAC1B;aAEF,CAAC;YACF,IAAI,KAAK,GAAG,IAAI,UAAU,CAAC,OAAO,CAAC,CAAC;QAEtC,CAAC,CAAC,CAAC;IAGL,CAAC,CAAC,CAAC;AAGL,CAAC,CAAC,CAAC"}
@@ -0,0 +1,21 @@
1
+ /// <reference types="node" />
2
+ /// <reference types="node" />
3
+ /// <reference types="node" />
4
+ import net from 'net';
5
+ import tls, { TlsOptions } from 'tls';
6
+ import Connection from 'mqtt-connection';
7
+ import { Duplex } from 'stream';
8
+ export type MqttServerListener = (client: Connection) => void;
9
+ export declare class MqttServer extends net.Server {
10
+ connectionList: Duplex[];
11
+ constructor(listener: MqttServerListener);
12
+ }
13
+ export declare class MqttServerNoWait extends net.Server {
14
+ connectionList: Duplex[];
15
+ constructor(listener: MqttServerListener);
16
+ }
17
+ export declare class MqttSecureServer extends tls.Server {
18
+ connectionList: Duplex[];
19
+ constructor(opts: TlsOptions, listener: MqttServerListener);
20
+ setupConnection(duplex: Duplex): void;
21
+ }
package/dist/server.js ADDED
@@ -0,0 +1,63 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MqttSecureServer = exports.MqttServerNoWait = exports.MqttServer = void 0;
4
+ const net_1 = require("net");
5
+ const tls_1 = require("tls");
6
+ const mqtt_connection_1 = require("mqtt-connection");
7
+ class MqttServer extends net_1.default.Server {
8
+ constructor(listener) {
9
+ super();
10
+ this.connectionList = [];
11
+ this.on('connection', (duplex) => {
12
+ this.connectionList.push(duplex);
13
+ const connection = new mqtt_connection_1.default(duplex, () => {
14
+ this.emit('client', connection);
15
+ });
16
+ });
17
+ if (listener) {
18
+ this.on('client', listener);
19
+ }
20
+ }
21
+ }
22
+ exports.MqttServer = MqttServer;
23
+ class MqttServerNoWait extends net_1.default.Server {
24
+ constructor(listener) {
25
+ super();
26
+ this.connectionList = [];
27
+ this.on('connection', (duplex) => {
28
+ this.connectionList.push(duplex);
29
+ const connection = new mqtt_connection_1.default(duplex);
30
+ this.emit('client', connection);
31
+ });
32
+ if (listener) {
33
+ this.on('client', listener);
34
+ }
35
+ }
36
+ }
37
+ exports.MqttServerNoWait = MqttServerNoWait;
38
+ class MqttSecureServer extends tls_1.default.Server {
39
+ constructor(opts, listener) {
40
+ if (typeof opts === 'function') {
41
+ listener = opts;
42
+ opts = {};
43
+ }
44
+ super(opts);
45
+ this.connectionList = [];
46
+ this.on('secureConnection', (socket) => {
47
+ this.connectionList.push(socket);
48
+ const connection = new mqtt_connection_1.default(socket, () => {
49
+ this.emit('client', connection);
50
+ });
51
+ });
52
+ if (listener) {
53
+ this.on('client', listener);
54
+ }
55
+ }
56
+ setupConnection(duplex) {
57
+ const connection = new mqtt_connection_1.default(duplex, () => {
58
+ this.emit('client', connection);
59
+ });
60
+ }
61
+ }
62
+ exports.MqttSecureServer = MqttSecureServer;
63
+ //# sourceMappingURL=server.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server.js","sourceRoot":"","sources":["../test/server.ts"],"names":[],"mappings":";;;AAAA,6BAAqB;AACrB,6BAAqC;AACrC,qDAAwC;AAUxC,MAAa,UAAW,SAAQ,aAAG,CAAC,MAAM;IAGzC,YAAY,QAA4B;QACvC,KAAK,EAAE,CAAA;QACP,IAAI,CAAC,cAAc,GAAG,EAAE,CAAA;QAExB,IAAI,CAAC,EAAE,CAAC,YAAY,EAAE,CAAC,MAAM,EAAE,EAAE;YAChC,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC,MAAM,CAAC,CAAA;YAChC,MAAM,UAAU,GAAG,IAAI,yBAAU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MAAM,UAAU,GAAG,IAAI,yBAAU,CAAC,MAAM,EAAE,GAAG,EAAE;gBAC9C,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,UAAU,CAAC,CAAA;YAChC,CAAC,CAAC,CAAA;QACH,CAAC,CAAC,CAAA;QAEF,IAAI,QAAQ,EAAE,CAAC;YACd,IAAI,CAAC,EAAE,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAA;QAC5B,CAAC;IACF,CAAC;IAED,eAAe,CAAC,MAAc;QAC7B,MAAM,UAAU,GAAG,IAAI,yBAAU,CAAC,MAAM,EAAE,GAAG,EAAE;YAC9C,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,UAAU,CAAC,CAAA;QAChC,CAAC,CAAC,CAAA;IACH,CAAC;CACD;AA9BD,4CA8BC"}
@@ -0,0 +1,4 @@
1
+ /// <reference types="node" />
2
+ import { MqttServerListener } from './server';
3
+ import { Server } from 'net';
4
+ export default function serverBuilder(protocol: string, handler?: MqttServerListener): Server;
@@ -0,0 +1,153 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const server_1 = require("./server");
4
+ const debug_1 = require("debug");
5
+ const path_1 = require("path");
6
+ const fs_1 = require("fs");
7
+ const http_1 = require("http");
8
+ const ws_1 = require("ws");
9
+ const mqtt_connection_1 = require("mqtt-connection");
10
+ const KEY = path_1.default.join(__dirname, 'helpers', 'tls-key.pem');
11
+ const CERT = path_1.default.join(__dirname, 'helpers', 'tls-cert.pem');
12
+ const debug = (0, debug_1.default)('mqttjs:server_helpers_for_client_tests');
13
+ function serverBuilder(protocol, handler) {
14
+ const sockets = [];
15
+ const defaultHandler = (serverClient) => {
16
+ sockets.push(serverClient);
17
+ serverClient.on('auth', (packet) => {
18
+ if (serverClient.writable)
19
+ return false;
20
+ const rc = 'reasonCode';
21
+ const connack = {};
22
+ connack[rc] = 0;
23
+ serverClient.connack(connack);
24
+ });
25
+ serverClient.on('connect', (packet) => {
26
+ if (!serverClient.writable)
27
+ return false;
28
+ let rc = 'returnCode';
29
+ const connack = {};
30
+ if (serverClient.options.protocolVersion >= 4) {
31
+ connack['sessionPresent'] = false;
32
+ }
33
+ if (serverClient.options &&
34
+ serverClient.options.protocolVersion === 5) {
35
+ rc = 'reasonCode';
36
+ if (packet.clientId === 'invalid') {
37
+ connack[rc] = 128;
38
+ }
39
+ else {
40
+ connack[rc] = 0;
41
+ }
42
+ }
43
+ else if (packet.clientId === 'invalid') {
44
+ connack[rc] = 2;
45
+ }
46
+ else {
47
+ connack[rc] = 0;
48
+ }
49
+ if (packet.properties && packet.properties.authenticationMethod) {
50
+ return false;
51
+ }
52
+ serverClient.connack(connack);
53
+ });
54
+ serverClient.on('publish', (packet) => {
55
+ if (!serverClient.writable)
56
+ return false;
57
+ setImmediate(() => {
58
+ switch (packet.qos) {
59
+ case 0:
60
+ break;
61
+ case 1:
62
+ serverClient.puback(packet);
63
+ break;
64
+ case 2:
65
+ serverClient.pubrec(packet);
66
+ break;
67
+ }
68
+ });
69
+ });
70
+ serverClient.on('pubrel', (packet) => {
71
+ if (!serverClient.writable)
72
+ return false;
73
+ serverClient.pubcomp(packet);
74
+ });
75
+ serverClient.on('pubrec', (packet) => {
76
+ if (!serverClient.writable)
77
+ return false;
78
+ serverClient.pubrel(packet);
79
+ });
80
+ serverClient.on('pubcomp', () => {
81
+ });
82
+ serverClient.on('subscribe', (packet) => {
83
+ if (!serverClient.writable)
84
+ return false;
85
+ serverClient.suback({
86
+ messageId: packet.messageId,
87
+ granted: packet.subscriptions.map((e) => e.qos),
88
+ });
89
+ });
90
+ serverClient.on('unsubscribe', (packet) => {
91
+ if (!serverClient.writable)
92
+ return false;
93
+ packet.granted = packet.unsubscriptions.map(() => 0);
94
+ serverClient.unsuback(packet);
95
+ });
96
+ serverClient.on('pingreq', () => {
97
+ if (!serverClient.writable)
98
+ return false;
99
+ serverClient.pingresp();
100
+ });
101
+ serverClient.on('end', () => {
102
+ debug('disconnected from server');
103
+ const index = sockets.findIndex((s) => s === serverClient);
104
+ if (index !== -1) {
105
+ sockets.splice(index, 1);
106
+ }
107
+ });
108
+ };
109
+ if (!handler) {
110
+ handler = defaultHandler;
111
+ }
112
+ let mqttServer = null;
113
+ if (protocol === 'mqtt') {
114
+ mqttServer = new server_1.MqttServer(handler);
115
+ }
116
+ if (protocol === 'mqtts') {
117
+ mqttServer = new server_1.MqttSecureServer({
118
+ key: fs_1.default.readFileSync(KEY),
119
+ cert: fs_1.default.readFileSync(CERT),
120
+ }, handler);
121
+ }
122
+ if (protocol === 'ws') {
123
+ const attachWebsocketServer = (server) => {
124
+ const webSocketServer = new ws_1.default.Server({
125
+ server,
126
+ perMessageDeflate: false,
127
+ });
128
+ webSocketServer.on('connection', (ws) => {
129
+ const stream = ws_1.default.createWebSocketStream(ws);
130
+ const connection = new mqtt_connection_1.default(stream);
131
+ connection.protocol = ws.protocol;
132
+ server.emit('client', connection);
133
+ stream.on('error', () => { });
134
+ connection.on('error', () => { });
135
+ connection.on('close', () => { });
136
+ });
137
+ };
138
+ const httpServer = http_1.default.createServer();
139
+ attachWebsocketServer(httpServer);
140
+ httpServer.on('client', handler);
141
+ mqttServer = httpServer;
142
+ }
143
+ const originalClose = mqttServer.close;
144
+ mqttServer.close = (cb) => {
145
+ sockets.forEach((socket) => {
146
+ socket.destroy();
147
+ });
148
+ originalClose.call(mqttServer, cb);
149
+ };
150
+ return mqttServer;
151
+ }
152
+ exports.default = serverBuilder;
153
+ //# sourceMappingURL=server_helpers_for_client_tests.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server_helpers_for_client_tests.js","sourceRoot":"","sources":["../test/server_helpers_for_client_tests.ts"],"names":[],"mappings":";;AAAA,qCAA2E;AAC3E,iCAA0B;AAE1B,+BAAuB;AACvB,2BAAmB;AAEnB,+BAAuB;AACvB,2BAA0B;AAC1B,qDAA4C;AAG5C,MAAM,GAAG,GAAG,cAAI,CAAC,IAAI,CAAC,SAAS,EAAE,SAAS,EAAE,aAAa,C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OAAO,EAAE,GAAG,EAAE,GAAE,CAAC,CAAC,CAAA;gBAChC,UAAU,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,EAAE,GAAE,CAAC,CAAC,CAAA;YACjC,CAAC,CAAC,CAAA;QACH,CAAC,CAAA;QAED,MAAM,UAAU,GAAG,cAAI,CAAC,YAAY,EAAE,CAAA;QAEtC,qBAAqB,CAAC,UAAU,CAAC,CAAA;QACjC,UAAU,CAAC,EAAE,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAA;QAChC,UAAU,GAAG,UAAU,CAAA;IACxB,CAAC;IAED,MAAM,aAAa,GAAG,UAAU,CAAC,KAAK,CAAA;IACtC,UAAU,CAAC,KAAK,GAAG,CAAC,EAAE,EAAE,EAAE;QACzB,OAAO,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,EAAE;YAC1B,MAAM,CAAC,OAAO,EAAE,CAAA;QACjB,CAAC,CAAC,CAAA;QACF,aAAa,CAAC,IAAI,CAAC,UAAU,EAAE,EAAE,CAAC,CAAA;IACnC,CAAC,CAAA;IAED,OAAO,UAAU,CAAA;AAClB,CAAC;AAzJD,gCAyJC"}
package/lib/alexaLocal.js CHANGED
@@ -117,6 +117,7 @@ function alexaLocal(options) {
117
117
  });
118
118
 
119
119
  connection.client.on('error', function (err) {
120
+ console.log('ERROR:', err.message, err.code, err)
120
121
  if (options.alexaService) {
121
122
  options.alexaService.setCharacteristic(Characteristic.ContactSensorState, Characteristic.ContactSensorState.CONTACT_NOT_DETECTED);
122
123
  }
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "homebridge-alexa",
3
- "version": "0.6.9-beta.0",
3
+ "version": "0.6.9-beta.2",
4
4
  "description": "Control your Homebridge devices with Amazon Alexa.",
5
5
  "main": "plugin.js",
6
6
  "scripts": {
7
- "test": "echo \"Error: no test specified\" && exit 1",
7
+ "test": "jest --forceExit --detectOpenHandles --verbose=true --silent ",
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 --insert README.md;./gh-md-toc --insert Troubleshooting.md;./gh-md-toc --insert 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"
@@ -27,15 +27,21 @@
27
27
  "alexa",
28
28
  "homebridge-plugin"
29
29
  ],
30
- "engines": {
31
- "node": ">=4.4.5",
32
- "homebridge": ">=0.4.16"
33
- },
34
30
  "devDependencies": {
35
31
  "@oznu/hap-client": "^1.1.3",
32
+ "@types/jest": "^29.5.10",
33
+ "@types/node": "^20.10.0",
34
+ "babel-jest": "^29.7.0",
36
35
  "documentation": "^14.0.2",
36
+ "jest": "^29.7.0",
37
+ "mqtt-connection": "^4.1.0",
37
38
  "nodemon": "^3.0.1",
38
- "semver": "^7.5.4"
39
+ "rimraf": "^5.0.5",
40
+ "semver": "^7.5.4",
41
+ "ts-jest": "^29.1.1",
42
+ "ts-node": "^10.9.1",
43
+ "typescript": "^5.3.2",
44
+ "ws": "^8.14.2"
39
45
  },
40
46
  "dependencies": {
41
47
  "bottleneck": "2.19.5",
@@ -0,0 +1,63 @@
1
+ import serverBuilder from './server_helpers_for_client_tests';
2
+ var AlexaLocal = require('../lib/alexaLocal.js').alexaLocal;
3
+
4
+ jest.setTimeout(30000);
5
+
6
+
7
+ describe('MQTT Client', () => {
8
+ beforeAll(async () => {
9
+
10
+ var version;
11
+ let client = null
12
+ let publishCount = 0
13
+ const server2 = serverBuilder('mqtt', (serverClient) => {
14
+ serverClient.on('connect', () => {
15
+ console.log('connect');
16
+ const connack =
17
+ version === 5 ? { reasonCode: 0 } : { returnCode: 0 }
18
+ serverClient.connack(connack)
19
+ })
20
+ serverClient.on('publish', (packet) => {
21
+ console.log('publish', packet.payload.toString());
22
+ if (packet.qos !== 0) {
23
+ serverClient.puback({ messageId: packet.messageId })
24
+ }
25
+ })
26
+ })
27
+ }, 300000);
28
+
29
+ afterAll(async () => {
30
+
31
+ // await sleep(10000)
32
+
33
+ });
34
+
35
+ describe('Validate Inital Startup', () => {
36
+ test('getconf GNU_LIBC_VERSION', async () => {
37
+ var options = {
38
+ // MQTT Options
39
+ log: console.log,
40
+ mqttURL: 'mqtt://localhost:1883',
41
+ transport: 'mqtt',
42
+ mqttOptions: {
43
+ username: 'TEST',
44
+ password: 'PASSWORD',
45
+ reconnectPeriod: 33, // Increased reconnect period to allow DDOS protection to reset
46
+ keepalive: 55,
47
+ rejectUnauthorized: false
48
+ },
49
+
50
+ };
51
+ var alexa = new AlexaLocal(options);
52
+ await sleep(10000)
53
+ });
54
+
55
+
56
+ });
57
+
58
+
59
+ });
60
+
61
+ async function sleep(ms) {
62
+ return new Promise(resolve => setTimeout(resolve, ms));
63
+ }
package/test/jest.json ADDED
@@ -0,0 +1,12 @@
1
+ {
2
+ "moduleFileExtensions": ["js", "json", "ts"],
3
+ "rootDir": "../",
4
+ "testEnvironment": "node",
5
+ "testRegex": ".test.ts$",
6
+ "testTimeout": 10000,
7
+ "transform": {
8
+ "^.+\\.(t)s$": "ts-jest"
9
+ },
10
+ "collectCoverageFrom": ["**/*.ts"],
11
+ "coveragePathIgnorePatterns": ["/ui/", "/test/", "/dist/", "/scripts/"]
12
+ }
package/test/server.ts ADDED
@@ -0,0 +1,95 @@
1
+ import * as net from 'net'
2
+ import { TlsOptions } from 'tls'
3
+ import * as tls from 'tls'
4
+ import Connection from 'mqtt-connection'
5
+ import { Duplex } from 'stream'
6
+
7
+ export type MqttServerListener = (client: Connection) => void
8
+
9
+ /**
10
+ * MqttServer
11
+ *
12
+ * @param {Function} listener - fired on client connection
13
+ */
14
+ export class MqttServer extends net.Server {
15
+ connectionList: Duplex[]
16
+
17
+ constructor(listener: MqttServerListener) {
18
+ super()
19
+ this.connectionList = []
20
+
21
+ this.on('connection', (duplex) => {
22
+ this.connectionList.push(duplex)
23
+ const connection = new Connection(duplex, () => {
24
+ this.emit('client', connection)
25
+ })
26
+ })
27
+
28
+ if (listener) {
29
+ this.on('client', listener)
30
+ }
31
+ }
32
+ }
33
+
34
+ /**
35
+ * MqttServerNoWait (w/o waiting for initialization)
36
+ *
37
+ * @param {Function} listener - fired on client connection
38
+ */
39
+ export class MqttServerNoWait extends net.Server {
40
+ connectionList: Duplex[]
41
+
42
+ constructor(listener: MqttServerListener) {
43
+ super()
44
+ this.connectionList = []
45
+
46
+ this.on('connection', (duplex) => {
47
+ this.connectionList.push(duplex)
48
+ const connection = new Connection(duplex)
49
+ // do not wait for connection to return to send it to the client.
50
+ this.emit('client', connection)
51
+ })
52
+
53
+ if (listener) {
54
+ this.on('client', listener)
55
+ }
56
+ }
57
+ }
58
+
59
+ /**
60
+ * MqttSecureServer
61
+ *
62
+ * @param {Object} opts - server options
63
+ * @param {Function} listener
64
+ */
65
+ export class MqttSecureServer extends tls.Server {
66
+ connectionList: Duplex[]
67
+
68
+ constructor(opts: TlsOptions, listener: MqttServerListener) {
69
+ if (typeof opts === 'function') {
70
+ listener = opts
71
+ opts = {}
72
+ }
73
+
74
+ // sets a listener for the 'connection' event
75
+ super(opts)
76
+ this.connectionList = []
77
+
78
+ this.on('secureConnection', (socket) => {
79
+ this.connectionList.push(socket)
80
+ const connection = new Connection(socket, () => {
81
+ this.emit('client', connection)
82
+ })
83
+ })
84
+
85
+ if (listener) {
86
+ this.on('client', listener)
87
+ }
88
+ }
89
+
90
+ setupConnection(duplex: Duplex) {
91
+ const connection = new Connection(duplex, () => {
92
+ this.emit('client', connection)
93
+ })
94
+ }
95
+ }
@@ -0,0 +1,176 @@
1
+ import { MqttServer, MqttSecureServer, MqttServerListener } from './server'
2
+ import _debug from 'debug'
3
+
4
+ import * as path from 'path'
5
+ import * as fs from 'fs'
6
+
7
+ import * as http from 'http'
8
+ import WebSocket from 'ws'
9
+ import MQTTConnection from 'mqtt-connection'
10
+ import { Server } from 'net'
11
+
12
+ const KEY = path.join(__dirname, 'helpers', 'tls-key.pem')
13
+ const CERT = path.join(__dirname, 'helpers', 'tls-cert.pem')
14
+
15
+ const debug = _debug('mqttjs:server_helpers_for_client_tests')
16
+
17
+ /**
18
+ * This will build the client for the server to use during testing, and set up the
19
+ * server side client based on mqtt-connection for handling MQTT messages.
20
+ * @param {String} protocol - 'mqtt', 'mqtts' or 'ws'
21
+ * @param {Function} handler - event handler
22
+ */
23
+ export default function serverBuilder(
24
+ protocol: string,
25
+ handler?: MqttServerListener,
26
+ ): Server {
27
+ const sockets = []
28
+ const defaultHandler: MqttServerListener = (serverClient) => {
29
+ sockets.push(serverClient)
30
+ serverClient.on('auth', (packet) => {
31
+ if (serverClient.writable) return false
32
+ const rc = 'reasonCode'
33
+ const connack = {}
34
+ connack[rc] = 0
35
+ serverClient.connack(connack)
36
+ })
37
+ serverClient.on('connect', (packet) => {
38
+ if (!serverClient.writable) return false
39
+ let rc = 'returnCode'
40
+ const connack = {}
41
+ if (serverClient.options.protocolVersion >= 4) {
42
+ connack['sessionPresent'] = false
43
+ }
44
+ if (
45
+ serverClient.options &&
46
+ serverClient.options.protocolVersion === 5
47
+ ) {
48
+ rc = 'reasonCode'
49
+ if (packet.clientId === 'invalid') {
50
+ connack[rc] = 128
51
+ } else {
52
+ connack[rc] = 0
53
+ }
54
+ } else if (packet.clientId === 'invalid') {
55
+ connack[rc] = 2
56
+ } else {
57
+ connack[rc] = 0
58
+ }
59
+ if (packet.properties && packet.properties.authenticationMethod) {
60
+ return false
61
+ }
62
+ serverClient.connack(connack)
63
+ })
64
+
65
+ serverClient.on('publish', (packet) => {
66
+ if (!serverClient.writable) return false
67
+ setImmediate(() => {
68
+ switch (packet.qos) {
69
+ case 0:
70
+ break
71
+ case 1:
72
+ serverClient.puback(packet)
73
+ break
74
+ case 2:
75
+ serverClient.pubrec(packet)
76
+ break
77
+ }
78
+ })
79
+ })
80
+
81
+ serverClient.on('pubrel', (packet) => {
82
+ if (!serverClient.writable) return false
83
+ serverClient.pubcomp(packet)
84
+ })
85
+
86
+ serverClient.on('pubrec', (packet) => {
87
+ if (!serverClient.writable) return false
88
+ serverClient.pubrel(packet)
89
+ })
90
+
91
+ serverClient.on('pubcomp', () => {
92
+ // Nothing to be done
93
+ })
94
+
95
+ serverClient.on('subscribe', (packet) => {
96
+ if (!serverClient.writable) return false
97
+ serverClient.suback({
98
+ messageId: packet.messageId,
99
+ granted: packet.subscriptions.map((e) => e.qos),
100
+ })
101
+ })
102
+
103
+ serverClient.on('unsubscribe', (packet) => {
104
+ if (!serverClient.writable) return false
105
+ packet.granted = packet.unsubscriptions.map(() => 0)
106
+ serverClient.unsuback(packet)
107
+ })
108
+
109
+ serverClient.on('pingreq', () => {
110
+ if (!serverClient.writable) return false
111
+ serverClient.pingresp()
112
+ })
113
+
114
+ serverClient.on('end', () => {
115
+ debug('disconnected from server')
116
+ const index = sockets.findIndex((s) => s === serverClient)
117
+ if (index !== -1) {
118
+ sockets.splice(index, 1)
119
+ }
120
+ })
121
+ }
122
+
123
+ if (!handler) {
124
+ handler = defaultHandler
125
+ }
126
+
127
+ let mqttServer = null
128
+
129
+ if (protocol === 'mqtt') {
130
+ mqttServer = new MqttServer(handler)
131
+ }
132
+ if (protocol === 'mqtts') {
133
+ mqttServer = new MqttSecureServer(
134
+ {
135
+ key: fs.readFileSync(KEY),
136
+ cert: fs.readFileSync(CERT),
137
+ },
138
+ handler,
139
+ )
140
+ }
141
+ if (protocol === 'ws') {
142
+ const attachWebsocketServer = (server) => {
143
+ const webSocketServer = new WebSocket.Server({
144
+ server,
145
+ perMessageDeflate: false,
146
+ })
147
+
148
+ webSocketServer.on('connection', (ws) => {
149
+ // server.connectionList.push(ws)
150
+ const stream = WebSocket.createWebSocketStream(ws)
151
+ const connection = new MQTTConnection(stream)
152
+ connection.protocol = ws.protocol
153
+ server.emit('client', connection)
154
+ stream.on('error', () => {})
155
+ connection.on('error', () => {})
156
+ connection.on('close', () => {})
157
+ })
158
+ }
159
+
160
+ const httpServer = http.createServer()
161
+ // httpServer.connectionList = []
162
+ attachWebsocketServer(httpServer)
163
+ httpServer.on('client', handler)
164
+ mqttServer = httpServer
165
+ }
166
+
167
+ const originalClose = mqttServer.close
168
+ mqttServer.close = (cb) => {
169
+ sockets.forEach((socket) => {
170
+ socket.destroy()
171
+ })
172
+ originalClose.call(mqttServer, cb)
173
+ }
174
+
175
+ return mqttServer
176
+ }
@@ -0,0 +1,11 @@
1
+ {
2
+ "extends": "./tsconfig.json",
3
+ "exclude": [
4
+ "node_modules",
5
+ "test",
6
+ "**/*spec.ts",
7
+ "ui",
8
+ "public",
9
+ "scripts"
10
+ ]
11
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,19 @@
1
+ {
2
+ "compilerOptions": {
3
+ "module": "commonjs",
4
+ "declaration": true,
5
+ "removeComments": true,
6
+ "emitDecoratorMetadata": true,
7
+ "experimentalDecorators": true,
8
+ "target": "es2020",
9
+ "sourceMap": true,
10
+ "outDir": "./dist",
11
+ "baseUrl": "./",
12
+ },
13
+ "exclude": [
14
+ "node_modules",
15
+ "./dist",
16
+ "ui",
17
+ "public"
18
+ ]
19
+ }