mirror of
https://github.com/bourquep/mysa-js-sdk.git
synced 2026-02-04 09:41:07 +00:00
Compare commits
30 Commits
v1.3.3
...
dependabot
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a9822a104e | ||
|
|
85c123d2aa | ||
|
|
0524bcea73 | ||
|
|
bb10ba4616 | ||
|
|
5366ea6fc9 | ||
|
|
baa7941cfc | ||
|
|
ef60db37d5 | ||
|
|
f1525cd1f1 | ||
|
|
3b2a020ac7 | ||
|
|
cbac285b1e | ||
|
|
ca127483c1 | ||
|
|
e320d658e8 | ||
|
|
c8dac38563 | ||
|
|
94acdede23 | ||
|
|
d007c2d745 | ||
|
|
5d9981f9e0 | ||
|
|
2f2cdef0ee | ||
|
|
193f67226b | ||
|
|
ef8d787e05 | ||
|
|
0c71ed95ce | ||
|
|
d861a50136 | ||
|
|
7b332b1416 | ||
|
|
15edd9dbbf | ||
|
|
0c906fefe9 | ||
|
|
137e51efa0 | ||
|
|
5644bd7a1e | ||
|
|
e434b96087 | ||
|
|
bec3a9804d | ||
|
|
64ba134b76 | ||
|
|
8dfb1b7e82 |
@@ -11,6 +11,13 @@
|
||||
"avatar_url": "https://avatars.githubusercontent.com/u/227265405?v=4",
|
||||
"profile": "https://github.com/jagmandan",
|
||||
"contributions": ["code"]
|
||||
},
|
||||
{
|
||||
"login": "remiolivier",
|
||||
"name": "remiolivier",
|
||||
"avatar_url": "https://avatars.githubusercontent.com/u/1379047?v=4",
|
||||
"profile": "https://github.com/remiolivier",
|
||||
"contributions": ["code"]
|
||||
}
|
||||
],
|
||||
"contributorsPerLine": 7,
|
||||
|
||||
2
.github/dependabot.yml
vendored
2
.github/dependabot.yml
vendored
@@ -8,7 +8,7 @@ updates:
|
||||
- package-ecosystem: 'npm' # See documentation for possible values
|
||||
directory: '/' # Location of package manifests
|
||||
schedule:
|
||||
interval: 'daily'
|
||||
interval: 'weekly'
|
||||
labels:
|
||||
- 'dependencies'
|
||||
commit-message:
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->
|
||||
|
||||
[](#contributors-)
|
||||
[](#contributors-)
|
||||
|
||||
<!-- ALL-CONTRIBUTORS-BADGE:END -->
|
||||
|
||||
@@ -247,6 +247,7 @@ Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/d
|
||||
<tbody>
|
||||
<tr>
|
||||
<td align="center" valign="top" width="14.28%"><a href="https://github.com/jagmandan"><img src="https://avatars.githubusercontent.com/u/227265405?v=4?s=100" width="100px;" alt="jagmandan"/><br /><sub><b>jagmandan</b></sub></a><br /><a href="https://github.com/bourquep/mysa-js-sdk/commits?author=jagmandan" title="Code">💻</a></td>
|
||||
<td align="center" valign="top" width="14.28%"><a href="https://github.com/remiolivier"><img src="https://avatars.githubusercontent.com/u/1379047?v=4?s=100" width="100px;" alt="remiolivier"/><br /><sub><b>remiolivier</b></sub></a><br /><a href="https://github.com/bourquep/mysa-js-sdk/commits?author=remiolivier" title="Code">💻</a></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
@@ -16,7 +16,8 @@ export default [
|
||||
rules: {
|
||||
'jsdoc/tag-lines': 'off',
|
||||
'jsdoc/check-tag-names': 'off',
|
||||
'jsdoc/valid-types': 'off'
|
||||
'jsdoc/valid-types': 'off',
|
||||
'jsdoc/require-throws-type': 'off'
|
||||
}
|
||||
},
|
||||
{ plugins: { tsdoc }, rules: { 'tsdoc/syntax': 'warn' } }
|
||||
|
||||
@@ -65,9 +65,10 @@ async function main() {
|
||||
client.emitter.on('statusChanged', (status) => {
|
||||
try {
|
||||
const device = devices.DevicesObj[status.deviceId];
|
||||
const watts = status.current !== undefined ? status.current * device.Voltage : undefined;
|
||||
const watts =
|
||||
status.current !== undefined && device.Voltage !== undefined ? status.current * device.Voltage : undefined;
|
||||
rootLogger.info(
|
||||
`'${device.Name}' status changed: ${status.temperature}°C, ${status.humidity}%, ${watts ?? 'na'}W`
|
||||
`[${status.deviceId}] '${device.Name ?? 'Unknown'}' status changed: ${status.temperature}°C, ${status.humidity}%, ${watts ?? 'na'}W`
|
||||
);
|
||||
} catch (error) {
|
||||
rootLogger.error(error, `Error processing status update for device '${status.deviceId}'`);
|
||||
@@ -77,7 +78,9 @@ async function main() {
|
||||
client.emitter.on('setPointChanged', (change) => {
|
||||
try {
|
||||
const device = devices.DevicesObj[change.deviceId];
|
||||
rootLogger.info(`'${device.Name}' setpoint changed from ${change.previousSetPoint} to ${change.newSetPoint}`);
|
||||
rootLogger.info(
|
||||
`'${device.Name ?? 'Unknown'}' setpoint changed from ${change.previousSetPoint} to ${change.newSetPoint}`
|
||||
);
|
||||
} catch (error) {
|
||||
rootLogger.error(error, `Error processing setpoint update for device '${change.deviceId}'`);
|
||||
}
|
||||
@@ -86,7 +89,7 @@ async function main() {
|
||||
client.emitter.on('stateChanged', (change) => {
|
||||
try {
|
||||
const device = devices.DevicesObj[change.deviceId];
|
||||
rootLogger.info(change, `'${device.Name}' state changed.`);
|
||||
rootLogger.info(change, `'${device.Name ?? 'Unknown'}' state changed.`);
|
||||
} catch (error) {
|
||||
rootLogger.error(error, `Error processing state update for device '${change.deviceId}'`);
|
||||
}
|
||||
@@ -96,7 +99,7 @@ async function main() {
|
||||
await Promise.all(
|
||||
Object.entries(devices.DevicesObj).map(async ([deviceId, device]) => {
|
||||
const serial = await client.getDeviceSerialNumber(deviceId);
|
||||
rootLogger.info(`Serial number for device '${deviceId}' (${device.Name}): ${serial}`);
|
||||
rootLogger.info(`Serial number for device '${deviceId}' (${device.Name ?? 'Unknown'}): ${serial}`);
|
||||
|
||||
await client.startRealtimeUpdates(deviceId);
|
||||
})
|
||||
|
||||
4000
package-lock.json
generated
4000
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
49
package.json
49
package.json
@@ -50,34 +50,35 @@
|
||||
"brace-expansion": "^2.0.2"
|
||||
},
|
||||
"dependencies": {
|
||||
"@aws-sdk/client-iot": "3.901.0",
|
||||
"@aws-sdk/credential-providers": "3.901.0",
|
||||
"amazon-cognito-identity-js": "6.3.15",
|
||||
"aws-iot-device-sdk-v2": "1.22.0",
|
||||
"dayjs": "1.11.13",
|
||||
"lodash": "4.17.21"
|
||||
"@aws-sdk/client-iot": "3.936.0",
|
||||
"@aws-sdk/credential-providers": "3.940.0",
|
||||
"amazon-cognito-identity-js": "6.3.16",
|
||||
"aws-iot-device-sdk-v2": "1.23.1",
|
||||
"dayjs": "1.11.19",
|
||||
"lodash": "4.17.23",
|
||||
"nanoid": "5.1.6"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "9.34.0",
|
||||
"@semantic-release/npm": "12.0.2",
|
||||
"@types/lodash": "4.17.20",
|
||||
"@types/node": "24.3.0",
|
||||
"@eslint/js": "9.39.1",
|
||||
"@semantic-release/npm": "13.1.2",
|
||||
"@types/lodash": "4.17.21",
|
||||
"@types/node": "24.10.1",
|
||||
"conventional-changelog-conventionalcommits": "9.1.0",
|
||||
"dotenv": "17.2.1",
|
||||
"eslint": "9.34.0",
|
||||
"eslint-plugin-jsdoc": "54.1.1",
|
||||
"eslint-plugin-tsdoc": "0.4.0",
|
||||
"pino": "9.13.0",
|
||||
"pino-pretty": "13.0.0",
|
||||
"dotenv": "17.2.3",
|
||||
"eslint": "9.39.1",
|
||||
"eslint-plugin-jsdoc": "61.4.1",
|
||||
"eslint-plugin-tsdoc": "0.5.0",
|
||||
"pino": "10.1.0",
|
||||
"pino-pretty": "13.1.2",
|
||||
"prettier": "3.6.2",
|
||||
"prettier-plugin-jsdoc": "1.3.3",
|
||||
"prettier-plugin-organize-imports": "4.2.0",
|
||||
"semantic-release": "24.2.7",
|
||||
"prettier-plugin-jsdoc": "1.5.0",
|
||||
"prettier-plugin-organize-imports": "4.3.0",
|
||||
"semantic-release": "25.0.2",
|
||||
"tsup": "8.5.0",
|
||||
"tsx": "4.20.3",
|
||||
"typedoc": "0.28.13",
|
||||
"typedoc-material-theme": "1.4.0",
|
||||
"typescript": "5.9.2",
|
||||
"typescript-eslint": "8.41.0"
|
||||
"tsx": "4.20.6",
|
||||
"typedoc": "0.28.14",
|
||||
"typedoc-material-theme": "1.4.1",
|
||||
"typescript": "5.9.3",
|
||||
"typescript-eslint": "8.46.2"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,3 +32,22 @@ export class MysaApiError extends Error {
|
||||
this.statusText = apiResponse.statusText;
|
||||
}
|
||||
}
|
||||
|
||||
/** Error thrown when an MQTT publish ultimately fails after retry attempts. */
|
||||
export class MqttPublishError extends Error {
|
||||
/**
|
||||
* Creates a new MqttPublishError instance.
|
||||
*
|
||||
* @param message - A human-readable description of the publish failure.
|
||||
* @param attempts - The number of attempts that were made before giving up.
|
||||
* @param original - The original error object thrown by the underlying MQTT library (optional).
|
||||
*/
|
||||
constructor(
|
||||
message: string,
|
||||
public attempts: number,
|
||||
public original?: unknown
|
||||
) {
|
||||
super(message);
|
||||
this.name = 'MqttPublishError';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,16 +19,28 @@ import {
|
||||
CognitoUserSession
|
||||
} from 'amazon-cognito-identity-js';
|
||||
import { iot, mqtt } from 'aws-iot-device-sdk-v2';
|
||||
import dayjs from 'dayjs';
|
||||
import { hash } from 'crypto';
|
||||
import dayjs, { Dayjs } from 'dayjs';
|
||||
import duration from 'dayjs/plugin/duration.js';
|
||||
import { MysaApiError, UnauthenticatedError } from './Errors';
|
||||
import { customAlphabet } from 'nanoid';
|
||||
import { MqttPublishError, MysaApiError, UnauthenticatedError } from './Errors';
|
||||
import { Logger, VoidLogger } from './Logger';
|
||||
import { MysaApiClientEventTypes } from './MysaApiClientEventTypes';
|
||||
import { MysaApiClientOptions } from './MysaApiClientOptions';
|
||||
import { MysaDeviceMode } from './MysaDeviceMode';
|
||||
import { MysaDeviceMode, MysaFanSpeedMode } from './MysaDeviceMode';
|
||||
|
||||
dayjs.extend(duration);
|
||||
|
||||
const getRandomClientId = customAlphabet('1234567890abcdefghijklmnopqrstuvwxyz', 8);
|
||||
|
||||
/** Options for MQTT publish operations. */
|
||||
export interface MqttPublishOptions {
|
||||
/** Maximum number of publish attempts before failing (default: 5). */
|
||||
maxAttempts?: number;
|
||||
/** Base delay in milliseconds used for exponential backoff calculation (default: 500). */
|
||||
baseDelayMs?: number;
|
||||
}
|
||||
|
||||
const AwsRegion = 'us-east-1';
|
||||
const CognitoUserPoolId = 'us-east-1_GUFWfhI7g';
|
||||
const CognitoClientId = '19efs8tgqe942atbqmot5m36t3';
|
||||
@@ -78,6 +90,18 @@ export class MysaApiClient {
|
||||
/** A promise that resolves to the MQTT connection used for real-time updates. */
|
||||
private _mqttConnectionPromise?: Promise<mqtt.MqttClientConnection>;
|
||||
|
||||
/** Stable per-process MQTT client id (prevents collisions between multiple processes). */
|
||||
private _mqttClientId?: string;
|
||||
|
||||
/** Expiration time of the credentials currently in use by the MQTT client. */
|
||||
private _mqttCredentialsExpiration?: Dayjs;
|
||||
|
||||
/** Interrupt timestamps for storm / collision detection. */
|
||||
private _mqttInterrupts: number[] = [];
|
||||
|
||||
/** Whether a forced MQTT reset is currently in progress (guards against re-entrancy). */
|
||||
private _mqttResetInProgress = false;
|
||||
|
||||
/** The device IDs that are currently being updated in real-time, mapped to their respective timeouts. */
|
||||
private _realtimeDeviceIds: Map<string, NodeJS.Timeout> = new Map();
|
||||
|
||||
@@ -165,6 +189,9 @@ export class MysaApiClient {
|
||||
async login(emailAddress: string, password: string): Promise<void> {
|
||||
this._cognitoUser = undefined;
|
||||
this._cognitoUserSession = undefined;
|
||||
this._mqttClientId = undefined;
|
||||
this._mqttInterrupts = [];
|
||||
|
||||
this.emitter.emit('sessionChanged', this.session);
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
@@ -210,7 +237,7 @@ export class MysaApiClient {
|
||||
async getDevices(): Promise<Devices> {
|
||||
this._logger.debug(`Fetching devices...`);
|
||||
|
||||
const session = await this.getFreshSession();
|
||||
const session = await this._getFreshSession();
|
||||
|
||||
const response = await this._fetcher(`${MysaApiBaseUrl}/devices`, {
|
||||
headers: {
|
||||
@@ -249,7 +276,7 @@ export class MysaApiClient {
|
||||
async getDeviceSerialNumber(deviceId: string): Promise<string | undefined> {
|
||||
this._logger.debug(`Fetching serial number for device ${deviceId}...`);
|
||||
|
||||
const session = await this.getFreshSession();
|
||||
const session = await this._getFreshSession();
|
||||
|
||||
// Get AWS credentials for IoT client
|
||||
const credentialsProvider = fromCognitoIdentityPool({
|
||||
@@ -292,7 +319,7 @@ export class MysaApiClient {
|
||||
async getDeviceFirmwares(): Promise<Firmwares> {
|
||||
this._logger.debug(`Fetching device firmwares...`);
|
||||
|
||||
const session = await this.getFreshSession();
|
||||
const session = await this._getFreshSession();
|
||||
|
||||
const response = await this._fetcher(`${MysaApiBaseUrl}/devices/firmware`, {
|
||||
headers: {
|
||||
@@ -317,7 +344,7 @@ export class MysaApiClient {
|
||||
async getDeviceStates(): Promise<DeviceStates> {
|
||||
this._logger.debug(`Fetching device states...`);
|
||||
|
||||
const session = await this.getFreshSession();
|
||||
const session = await this._getFreshSession();
|
||||
|
||||
const response = await this._fetcher(`${MysaApiBaseUrl}/devices/state`, {
|
||||
headers: {
|
||||
@@ -349,15 +376,20 @@ export class MysaApiClient {
|
||||
*
|
||||
* // Set temperature and mode
|
||||
* await client.setDeviceState('device123', 20, 'heat');
|
||||
*
|
||||
* // Set fan speed
|
||||
* await client.setDeviceState('device123', undefined, undefined, 'auto');
|
||||
* ```
|
||||
*
|
||||
* @param deviceId - The ID of the device to control.
|
||||
* @param setPoint - The target temperature set point (optional).
|
||||
* @param mode - The operating mode to set ('off', 'heat', or undefined to leave unchanged).
|
||||
* @param mode - The operating mode to set (one of MysaDeviceMode values, or undefined to leave unchanged).
|
||||
* @param fanSpeed - The fan speed mode to set ('low', 'medium', 'high', 'max', 'auto', or undefined to leave
|
||||
* unchanged).
|
||||
* @throws {@link UnauthenticatedError} When the user is not authenticated.
|
||||
* @throws {@link Error} When MQTT connection or command sending fails.
|
||||
*/
|
||||
async setDeviceState(deviceId: string, setPoint?: number, mode?: MysaDeviceMode) {
|
||||
async setDeviceState(deviceId: string, setPoint?: number, mode?: MysaDeviceMode, fanSpeed?: MysaFanSpeedMode) {
|
||||
this._logger.debug(`Setting device state for '${deviceId}'`);
|
||||
|
||||
if (!this._cachedDevices) {
|
||||
@@ -367,18 +399,21 @@ export class MysaApiClient {
|
||||
const device = this._cachedDevices.DevicesObj[deviceId];
|
||||
|
||||
this._logger.debug(`Initializing MQTT connection...`);
|
||||
const mqttConnection = await this.getMqttConnection();
|
||||
const mqttConnection = await this._getMqttConnection();
|
||||
|
||||
const now = dayjs();
|
||||
|
||||
this._logger.debug(`Sending request to set device state for '${deviceId}'...`);
|
||||
const modeMap = { off: 1, auto: 2, heat: 3, cool: 4, fan_only: 5, dry: 6 };
|
||||
const fanSpeedMap = { auto: 1, low: 3, medium: 5, high: 7, max: 8 };
|
||||
|
||||
const payload = serializeMqttPayload<ChangeDeviceState>({
|
||||
msg: InMessageType.CHANGE_DEVICE_STATE,
|
||||
id: now.valueOf(),
|
||||
time: now.unix(),
|
||||
ver: '1.0',
|
||||
src: {
|
||||
ref: this.session!.username,
|
||||
ref: this.session?.username ?? '',
|
||||
type: 100
|
||||
},
|
||||
dest: {
|
||||
@@ -390,22 +425,31 @@ export class MysaApiClient {
|
||||
ver: 1,
|
||||
type: device.Model.startsWith('BB-V1')
|
||||
? 1
|
||||
: device.Model.startsWith('BB-V2')
|
||||
? device.Model.endsWith('-L')
|
||||
? 5
|
||||
: 4
|
||||
: 0,
|
||||
: device.Model.startsWith('AC-V1')
|
||||
? 2
|
||||
: device.Model.startsWith('BB-V2')
|
||||
? device.Model.endsWith('-L')
|
||||
? 5
|
||||
: 4
|
||||
: 0,
|
||||
cmd: [
|
||||
{
|
||||
tm: -1,
|
||||
sp: setPoint,
|
||||
md: mode === 'off' ? 1 : mode === 'heat' ? 3 : undefined
|
||||
md: mode ? modeMap[mode] : undefined,
|
||||
fn: fanSpeed ? fanSpeedMap[fanSpeed] : undefined
|
||||
}
|
||||
]
|
||||
}
|
||||
});
|
||||
|
||||
await mqttConnection.publish(`/v1/dev/${deviceId}/in`, payload, mqtt.QoS.AtLeastOnce);
|
||||
try {
|
||||
await this._publishWithRetry(mqttConnection, `/v1/dev/${deviceId}/in`, payload, mqtt.QoS.AtLeastOnce);
|
||||
this._logger.debug(`Device state publish succeeded for '${deviceId}'`);
|
||||
} catch (error) {
|
||||
this._logger.error(`Failed to set device state for '${deviceId}'`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -438,11 +482,11 @@ export class MysaApiClient {
|
||||
}
|
||||
|
||||
this._logger.debug(`Initializing MQTT connection...`);
|
||||
const mqttConnection = await this.getMqttConnection();
|
||||
const mqttConnection = await this._getMqttConnection();
|
||||
|
||||
this._logger.debug(`Subscribing to MQTT topic '/v1/dev/${deviceId}/out'...`);
|
||||
await mqttConnection.subscribe(`/v1/dev/${deviceId}/out`, mqtt.QoS.AtLeastOnce, (_, payload) => {
|
||||
this.processMqttMessage(payload);
|
||||
this._processMqttMessage(payload);
|
||||
});
|
||||
|
||||
this._logger.debug(`Sending request to start publishing device status for '${deviceId}'...`);
|
||||
@@ -452,17 +496,19 @@ export class MysaApiClient {
|
||||
Timestamp: dayjs().unix(),
|
||||
Timeout: RealtimeKeepAliveInterval.asSeconds()
|
||||
});
|
||||
await mqttConnection.publish(`/v1/dev/${deviceId}/in`, payload, mqtt.QoS.AtLeastOnce);
|
||||
await this._publishWithRetry(mqttConnection, `/v1/dev/${deviceId}/in`, payload, mqtt.QoS.AtLeastOnce);
|
||||
|
||||
const timer = setInterval(async () => {
|
||||
this._logger.debug(`Sending request to keep-alive publishing device status for '${deviceId}'...`);
|
||||
|
||||
const connection = await this._getMqttConnection();
|
||||
const payload = serializeMqttPayload<StartPublishingDeviceStatus>({
|
||||
Device: deviceId,
|
||||
MsgType: InMessageType.START_PUBLISHING_DEVICE_STATUS,
|
||||
Timestamp: dayjs().unix(),
|
||||
Timeout: RealtimeKeepAliveInterval.asSeconds()
|
||||
});
|
||||
await mqttConnection.publish(`/v1/dev/${deviceId}/in`, payload, mqtt.QoS.AtLeastOnce);
|
||||
await this._publishWithRetry(connection, `/v1/dev/${deviceId}/in`, payload, mqtt.QoS.AtLeastOnce);
|
||||
}, RealtimeKeepAliveInterval.subtract(10, 'seconds').asMilliseconds());
|
||||
|
||||
this._realtimeDeviceIds.set(deviceId, timer);
|
||||
@@ -487,7 +533,7 @@ export class MysaApiClient {
|
||||
}
|
||||
|
||||
this._logger.debug(`Initializing MQTT connection...`);
|
||||
const mqttConnection = await this.getMqttConnection();
|
||||
const mqttConnection = await this._getMqttConnection();
|
||||
|
||||
this._logger.debug(`Unsubscribing to MQTT topic '/v1/dev/${deviceId}/out'...`);
|
||||
await mqttConnection.unsubscribe(`/v1/dev/${deviceId}/out`);
|
||||
@@ -505,7 +551,7 @@ export class MysaApiClient {
|
||||
* @returns A promise that resolves to a valid CognitoUserSession.
|
||||
* @throws {@link UnauthenticatedError} When no session exists or refresh fails.
|
||||
*/
|
||||
private async getFreshSession(): Promise<CognitoUserSession> {
|
||||
private async _getFreshSession(): Promise<CognitoUserSession> {
|
||||
if (!this._cognitoUser || !this._cognitoUserSession) {
|
||||
throw new UnauthenticatedError('An attempt was made to access a resource without a valid session.');
|
||||
}
|
||||
@@ -543,9 +589,9 @@ export class MysaApiClient {
|
||||
* @returns A promise that resolves to an active MQTT connection.
|
||||
* @throws {@link Error} When connection establishment fails.
|
||||
*/
|
||||
private getMqttConnection(): Promise<mqtt.MqttClientConnection> {
|
||||
private _getMqttConnection(): Promise<mqtt.MqttClientConnection> {
|
||||
if (!this._mqttConnectionPromise) {
|
||||
this._mqttConnectionPromise = this.createMqttConnection().catch((err) => {
|
||||
this._mqttConnectionPromise = this._createMqttConnection().catch((err) => {
|
||||
this._mqttConnectionPromise = undefined;
|
||||
throw err;
|
||||
});
|
||||
@@ -554,14 +600,109 @@ export class MysaApiClient {
|
||||
return this._mqttConnectionPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether an MQTT-related error is considered transient and worth retrying.
|
||||
*
|
||||
* Transient errors include timeouts, cancelled operations due to clean sessions, temporary connectivity loss, and
|
||||
* other recoverable network issues. Fatal errors (auth, permission, configuration) should not be retried at this
|
||||
* layer.
|
||||
*
|
||||
* @param err - The error object thrown by the underlying MQTT operation.
|
||||
* @returns True if the error appears transient and a retry should be attempted; false otherwise.
|
||||
*/
|
||||
private _isTransientMqttError(err: unknown): boolean {
|
||||
if (!err || typeof err !== 'object') {
|
||||
return false;
|
||||
}
|
||||
|
||||
const anyErr = err as { error_code?: unknown; error_name?: unknown; error?: unknown; message?: unknown };
|
||||
const code = anyErr.error_code || anyErr.error_name || anyErr.error;
|
||||
const msg = (anyErr.message || anyErr.error || '').toString();
|
||||
|
||||
const transientMarkers = [
|
||||
'AWS_ERROR_MQTT_TIMEOUT',
|
||||
'AWS_ERROR_MQTT_NO_CONNECTION',
|
||||
'AWS_ERROR_MQTT_UNEXPECTED_HANGUP',
|
||||
'UNEXPECTED_HANGUP',
|
||||
'AWS_ERROR_MQTT_CONNECTION_DESTROYED',
|
||||
'Time limit between request and response',
|
||||
'timeout'
|
||||
];
|
||||
|
||||
return transientMarkers.some((m) => (code && String(code).includes(m)) || msg.includes(m));
|
||||
}
|
||||
|
||||
/**
|
||||
* Publishes an MQTT message with exponential backoff retries for transient failures.
|
||||
*
|
||||
* Retries occur for errors classified by `_isTransientMqttError`. Between attempts the delay grows exponentially with
|
||||
* jitter to avoid thundering herds after broker recovery. If the connection is not currently marked as connected, a
|
||||
* reconnect is attempted; if that fails, the connection is rebuilt (fresh credentials) before the next retry.
|
||||
*
|
||||
* On final failure (after maxAttempts) a {@link MqttPublishError} is thrown including the number of attempts and
|
||||
* original error for higher-level handling.
|
||||
*
|
||||
* @remarks
|
||||
* Retry options fields:
|
||||
*
|
||||
* - MaxAttempts: Maximum number of publish attempts before failing (default: 5).
|
||||
* - BaseDelayMs: Base delay in milliseconds used for exponential backoff calculation (default: 500).
|
||||
*
|
||||
* @param connection - The active MQTT client connection used to send the publish.
|
||||
* @param topic - The MQTT topic to publish to.
|
||||
* @param payload - The serialized payload (binary buffer or Uint8Array).
|
||||
* @param qos - The desired MQTT QoS level for the publish.
|
||||
* @param opts - Retry options (defaults: maxAttempts=5, baseDelayMs=500).
|
||||
* @returns A promise that resolves when the publish succeeds, or rejects with {@link MqttPublishError}.
|
||||
*/
|
||||
private async _publishWithRetry(
|
||||
connection: mqtt.MqttClientConnection,
|
||||
topic: string,
|
||||
payload: ArrayBuffer | Uint8Array,
|
||||
qos: mqtt.QoS,
|
||||
opts: MqttPublishOptions = {}
|
||||
): Promise<void> {
|
||||
const maxAttempts = opts.maxAttempts ?? 5;
|
||||
const baseDelayMs = opts.baseDelayMs ?? 500;
|
||||
|
||||
let attempt = 0;
|
||||
|
||||
while (true) {
|
||||
attempt++;
|
||||
try {
|
||||
await connection.publish(topic, payload, qos);
|
||||
return;
|
||||
} catch (err) {
|
||||
const isTransient = this._isTransientMqttError(err);
|
||||
|
||||
if (!isTransient || attempt >= maxAttempts) {
|
||||
throw new MqttPublishError(`MQTT publish failed after ${attempt} attempts`, attempt, err);
|
||||
}
|
||||
|
||||
// Apply jitter: delay is randomized between 75% and 125% of the base exponential backoff
|
||||
const JITTER_MIN_FACTOR = 0.75;
|
||||
const JITTER_RANGE = 0.5;
|
||||
const delay = baseDelayMs * Math.pow(2, attempt - 1) * (JITTER_MIN_FACTOR + Math.random() * JITTER_RANGE);
|
||||
|
||||
this._logger.warn(
|
||||
`Transient MQTT publish error on '${topic}' (attempt ${attempt}/${maxAttempts}). Retrying in ${Math.round(
|
||||
delay
|
||||
)}ms`
|
||||
);
|
||||
|
||||
await new Promise((r) => setTimeout(r, delay));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new MQTT connection using AWS IoT WebSocket connections with Cognito credentials.
|
||||
*
|
||||
* @returns A promise that resolves to an active MQTT connection.
|
||||
* @throws {@link Error} When connection establishment fails.
|
||||
*/
|
||||
private async createMqttConnection(): Promise<mqtt.MqttClientConnection> {
|
||||
const session = await this.getFreshSession();
|
||||
private async _createMqttConnection(): Promise<mqtt.MqttClientConnection> {
|
||||
const session = await this._getFreshSession();
|
||||
const credentialsProvider = fromCognitoIdentityPool({
|
||||
clientConfig: {
|
||||
region: AwsRegion
|
||||
@@ -574,31 +715,144 @@ export class MysaApiClient {
|
||||
});
|
||||
const credentials = await credentialsProvider();
|
||||
|
||||
if (!credentials.expiration) {
|
||||
throw new Error('MQTT credentials do not have an expiration time.');
|
||||
}
|
||||
|
||||
this._mqttCredentialsExpiration = dayjs(credentials.expiration);
|
||||
|
||||
this._logger.debug(`MQTT credentials expiration: ${this._mqttCredentialsExpiration.format()}`);
|
||||
|
||||
if (!this._mqttCredentialsExpiration.isAfter(dayjs())) {
|
||||
this._mqttCredentialsExpiration = undefined;
|
||||
throw new Error('MQTT credentials are already expired.');
|
||||
}
|
||||
|
||||
// Per-process stable client id. Random suffix avoids collisions with other running processes.
|
||||
if (!this._mqttClientId) {
|
||||
const username = this.session?.username ?? 'anon';
|
||||
const usernameHash = hash('sha1', username);
|
||||
this._mqttClientId = `mysa-js-sdk-${usernameHash}-${process.pid}-${getRandomClientId()}`;
|
||||
}
|
||||
|
||||
const builder = iot.AwsIotMqttConnectionConfigBuilder.new_with_websockets()
|
||||
.with_credentials(AwsRegion, credentials.accessKeyId, credentials.secretAccessKey, credentials.sessionToken)
|
||||
.with_endpoint(MqttEndpoint)
|
||||
.with_client_id(`mysa-js-sdk-${dayjs().unix()}`) // Unique client ID
|
||||
.with_clean_session(true)
|
||||
.with_client_id(this._mqttClientId)
|
||||
.with_clean_session(false)
|
||||
.with_keep_alive_seconds(30)
|
||||
.with_ping_timeout_ms(3000)
|
||||
.with_protocol_operation_timeout_ms(60000);
|
||||
.with_protocol_operation_timeout_ms(60000)
|
||||
.with_reconnect_min_sec(1)
|
||||
.with_reconnect_max_sec(30);
|
||||
|
||||
const config = builder.build();
|
||||
const client = new mqtt.MqttClient();
|
||||
const connection = client.new_connection(config);
|
||||
|
||||
connection.on('connect', () => this._logger.debug('MQTT connect'));
|
||||
connection.on('connection_success', () => this._logger.debug('MQTT connection_success'));
|
||||
connection.on('connection_failure', (e) => this._logger.error('MQTT connection_failure', e));
|
||||
connection.on('interrupt', (e) => this._logger.warn('MQTT interrupt', e));
|
||||
connection.on('resume', (returnCode, sessionPresent) =>
|
||||
this._logger.info(`MQTT resume returnCode=${returnCode} sessionPresent=${sessionPresent}`)
|
||||
);
|
||||
connection.on('error', (e) => this._logger.error('MQTT error', e));
|
||||
connection.on('connect', () => {
|
||||
this._logger.debug(`MQTT connect (clientId=${this._mqttClientId})`);
|
||||
});
|
||||
|
||||
connection.on('connection_success', () => {
|
||||
this._logger.debug(`MQTT connection_success (clientId=${this._mqttClientId})`);
|
||||
});
|
||||
|
||||
connection.on('connection_failure', (e) => {
|
||||
this._logger.error(`MQTT connection_failure (clientId=${this._mqttClientId})`, e);
|
||||
});
|
||||
|
||||
connection.on('interrupt', async (e) => {
|
||||
this._logger.warn(`MQTT interrupt (clientId=${this._mqttClientId})`, e);
|
||||
|
||||
// Track recent interrupts
|
||||
const now = Date.now();
|
||||
|
||||
// Keep only last 60s
|
||||
this._mqttInterrupts = this._mqttInterrupts.filter((t) => now - t < 60000);
|
||||
this._mqttInterrupts.push(now);
|
||||
|
||||
const areCredentialsExpired = !(this._mqttCredentialsExpiration?.isAfter(dayjs()) ?? false);
|
||||
|
||||
if ((this._mqttInterrupts.length > 5 || areCredentialsExpired) && !this._mqttResetInProgress) {
|
||||
this._mqttResetInProgress = true;
|
||||
|
||||
if (this._mqttInterrupts.length > 5) {
|
||||
this._logger.warn(
|
||||
`High interrupt rate (${this._mqttInterrupts.length}/60s). Possible clientId collision. Regenerating clientId and resetting connection...`
|
||||
);
|
||||
} else {
|
||||
this._logger.warn(`Credentials expired. Regenerating clientId and resetting connection...`);
|
||||
}
|
||||
|
||||
// Force new client id to escape collision; close current connection
|
||||
this._mqttClientId = undefined;
|
||||
|
||||
this._mqttCredentialsExpiration = undefined;
|
||||
|
||||
// Clear interrupts
|
||||
this._mqttInterrupts = [];
|
||||
|
||||
// Explicitly clear promise first to prevent reuse while disconnecting
|
||||
// (publishers calling _getMqttConnection() will create a new one)
|
||||
this._mqttConnectionPromise = undefined;
|
||||
|
||||
try {
|
||||
await connection.disconnect();
|
||||
|
||||
try {
|
||||
this._logger.debug('Old MQTT connection disconnected; establishing new connection...');
|
||||
const newConnection = await this._getMqttConnection();
|
||||
|
||||
for (const deviceId of Array.from(this._realtimeDeviceIds.keys())) {
|
||||
const topic = `/v1/dev/${deviceId}/out`;
|
||||
this._logger.debug(`Re-subscribing to ${topic}`);
|
||||
await newConnection.subscribe(topic, mqtt.QoS.AtLeastOnce, (_topic, payload) => {
|
||||
this._processMqttMessage(payload);
|
||||
});
|
||||
}
|
||||
|
||||
this._logger.info('MQTT connection rebuilt successfully after interrupt storm or credentials expiration');
|
||||
} catch (err) {
|
||||
this._logger.error('Failed to re-subscribe after interrupt storm or credentials expiration', err);
|
||||
}
|
||||
} catch (error) {
|
||||
this._logger.error('Error during MQTT reset', error);
|
||||
} finally {
|
||||
this._mqttResetInProgress = false;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
connection.on('resume', async (returnCode, sessionPresent) => {
|
||||
this._logger.info(
|
||||
`MQTT resume returnCode=${returnCode} sessionPresent=${sessionPresent} clientId=${this._mqttClientId}`
|
||||
);
|
||||
|
||||
if (!sessionPresent) {
|
||||
this._logger.info('No session present, re-subscribing each device');
|
||||
try {
|
||||
for (const deviceId of Array.from(this._realtimeDeviceIds.keys())) {
|
||||
const topic = `/v1/dev/${deviceId}/out`;
|
||||
this._logger.debug(`Re-subscribing to ${topic}`);
|
||||
await connection.subscribe(topic, mqtt.QoS.AtLeastOnce, (_topic, payload) => {
|
||||
this._processMqttMessage(payload);
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
this._logger.error('Failed to re-subscribe after resume', err);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
connection.on('error', (e) => {
|
||||
this._logger.error(`MQTT error (clientId=${this._mqttClientId})`, e);
|
||||
});
|
||||
|
||||
connection.on('closed', () => {
|
||||
this._logger.info('MQTT connection closed');
|
||||
this._mqttConnectionPromise = undefined;
|
||||
this._mqttCredentialsExpiration = undefined;
|
||||
});
|
||||
|
||||
await connection.connect();
|
||||
@@ -615,7 +869,7 @@ export class MysaApiClient {
|
||||
*
|
||||
* @param payload - The raw MQTT message payload to process.
|
||||
*/
|
||||
private processMqttMessage(payload: ArrayBuffer) {
|
||||
private _processMqttMessage(payload: ArrayBuffer) {
|
||||
try {
|
||||
const parsedPayload = parseMqttPayload(payload);
|
||||
|
||||
@@ -653,13 +907,31 @@ export class MysaApiClient {
|
||||
});
|
||||
break;
|
||||
|
||||
case OutMessageType.DEVICE_STATE_CHANGE:
|
||||
case OutMessageType.DEVICE_STATE_CHANGE: {
|
||||
const modeMap: Record<number, MysaDeviceMode> = {
|
||||
1: 'off',
|
||||
2: 'auto',
|
||||
3: 'heat',
|
||||
4: 'cool',
|
||||
5: 'fan_only',
|
||||
6: 'dry'
|
||||
};
|
||||
const fanSpeedMap: Record<number, MysaFanSpeedMode> = {
|
||||
1: 'auto',
|
||||
3: 'low',
|
||||
5: 'medium',
|
||||
7: 'high',
|
||||
8: 'max'
|
||||
};
|
||||
|
||||
this.emitter.emit('stateChanged', {
|
||||
deviceId: parsedPayload.src.ref,
|
||||
mode: parsedPayload.body.state.md === 1 ? 'off' : parsedPayload.body.state.md === 3 ? 'heat' : undefined,
|
||||
setPoint: parsedPayload.body.state.sp
|
||||
mode: parsedPayload.body.state.md ? modeMap[parsedPayload.body.state.md] : undefined,
|
||||
setPoint: parsedPayload.body.state.sp,
|
||||
fanSpeed: parsedPayload.body.state.fn !== undefined ? fanSpeedMap[parsedPayload.body.state.fn] : undefined
|
||||
});
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
|
||||
@@ -4,4 +4,11 @@
|
||||
* Defines the possible operational states that a Mysa thermostat or heating device can be set to. These modes control
|
||||
* the device's heating behavior and power consumption.
|
||||
*/
|
||||
export type MysaDeviceMode = 'off' | 'heat';
|
||||
export type MysaDeviceMode = 'off' | 'heat' | 'cool' | 'dry' | 'fan_only' | 'auto';
|
||||
|
||||
/**
|
||||
* Union type representing the available fan speed modes for Mysa devices.
|
||||
*
|
||||
* Defines the possible fan speed states that a Mysa thermostat device can be set to.
|
||||
*/
|
||||
export type MysaFanSpeedMode = 'auto' | 'low' | 'medium' | 'high' | 'max';
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { MysaDeviceMode } from '@/api/MysaDeviceMode';
|
||||
import { MysaDeviceMode, MysaFanSpeedMode } from '@/api/MysaDeviceMode';
|
||||
|
||||
/**
|
||||
* Interface representing a device state change event for a Mysa device.
|
||||
@@ -14,4 +14,6 @@ export interface StateChange {
|
||||
mode?: MysaDeviceMode;
|
||||
/** Current temperature setpoint after the state change */
|
||||
setPoint: number;
|
||||
/** Optional fan speed (1 = auto, 3 = low, 5 = medium, 7 = high, 8 = max). AC only */
|
||||
fanSpeed?: MysaFanSpeedMode;
|
||||
}
|
||||
|
||||
@@ -36,6 +36,8 @@ export interface ChangeDeviceState extends MsgPayload<InMessageType.CHANGE_DEVIC
|
||||
md?: number;
|
||||
/** Unknown, should always be -1 */
|
||||
tm: number;
|
||||
/** Optional fan speed (1 = auto, 3 = low, 5 = medium, 7 = high, 8 = max). AC only */
|
||||
fn?: number;
|
||||
}
|
||||
];
|
||||
/**
|
||||
|
||||
@@ -25,10 +25,12 @@ export interface DeviceStateChange extends MsgPayload<OutMessageType.DEVICE_STAT
|
||||
ho: number;
|
||||
/** Unknown */
|
||||
lk: number;
|
||||
/** Device mode (1 = OFF, 3 = HEAT) */
|
||||
/** Device mode (1 = OFF, 2 = AUTO, 3 = HEAT, 4 = COOL, 5 = FAN_ONLY, 6 = DRY) */
|
||||
md: number;
|
||||
/** Temperature setpoint */
|
||||
sp: number;
|
||||
/** Optional fan speed (1 = auto, 3 = low, 5 = medium, 7 = high, 8 = max). AC only */
|
||||
fn?: number;
|
||||
};
|
||||
/** Success indicator for the state change operation (1 = success, 0 = failure) */
|
||||
success: number;
|
||||
|
||||
@@ -10,9 +10,9 @@ export interface BrandInfo {
|
||||
/** Unique identifier for the brand */
|
||||
Id: number;
|
||||
/** Remote control model number for the AC device */
|
||||
remoteModelNumber: string;
|
||||
remoteModelNumber?: string;
|
||||
/** Original Equipment Manufacturer brand name */
|
||||
OEMBrand: string;
|
||||
OEMBrand?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -56,55 +56,55 @@ export interface ModeObj {
|
||||
*/
|
||||
export interface DeviceBase {
|
||||
/** Button digital input configuration value */
|
||||
ButtonDI: number;
|
||||
ButtonDI?: number;
|
||||
/** Maximum current rating as a string value */
|
||||
MaxCurrent: string;
|
||||
MaxCurrent?: string;
|
||||
/** Device model identifier string */
|
||||
Model: string;
|
||||
/** Button average value configuration */
|
||||
ButtonAVE: number;
|
||||
ButtonAVE?: number;
|
||||
/** Operating voltage of the device */
|
||||
Voltage: number;
|
||||
Voltage?: number;
|
||||
/** Button polling interval configuration */
|
||||
ButtonPolling: number;
|
||||
ButtonPolling?: number;
|
||||
/** Minimum brightness level (0-100) */
|
||||
MinBrightness: number;
|
||||
MinBrightness?: number;
|
||||
/** User-assigned device name */
|
||||
Name: string;
|
||||
Name?: string;
|
||||
/** Button low power mode configuration */
|
||||
ButtonLowPower: number;
|
||||
ButtonLowPower?: number;
|
||||
/** Type of heater controlled by the device */
|
||||
HeaterType: string;
|
||||
HeaterType?: string;
|
||||
/** Button repeat delay configuration in milliseconds */
|
||||
ButtonRepeatDelay: number;
|
||||
ButtonRepeatDelay?: number;
|
||||
/** Button repeat start delay configuration in milliseconds */
|
||||
ButtonRepeatStart: number;
|
||||
ButtonRepeatStart?: number;
|
||||
/** Display animation style setting */
|
||||
Animation: string;
|
||||
Animation?: string;
|
||||
/** Maximum brightness level (0-100) */
|
||||
MaxBrightness: number;
|
||||
MaxBrightness?: number;
|
||||
/** Array of user IDs allowed to control this device */
|
||||
AllowedUsers: string[];
|
||||
AllowedUsers?: string[];
|
||||
/** Current button state indicator */
|
||||
ButtonState: string;
|
||||
ButtonState?: string;
|
||||
/** Home identifier that this device belongs to */
|
||||
Home: string;
|
||||
Home?: string;
|
||||
/** Button sensitivity threshold configuration */
|
||||
ButtonThreshold: number;
|
||||
ButtonThreshold?: number;
|
||||
/** Data format version used by the device */
|
||||
Format: string;
|
||||
Format?: string;
|
||||
/** Time zone setting for the device */
|
||||
TimeZone: string;
|
||||
TimeZone?: string;
|
||||
/** Unix timestamp of when device was last paired */
|
||||
LastPaired: number;
|
||||
LastPaired?: number;
|
||||
/** Minimum temperature setpoint allowed */
|
||||
MinSetpoint: number;
|
||||
MinSetpoint?: number;
|
||||
/** Current operating mode of the device */
|
||||
Mode: ModeObj;
|
||||
Mode?: ModeObj;
|
||||
/** User ID of the device owner */
|
||||
Owner: string;
|
||||
Owner?: string;
|
||||
/** Maximum temperature setpoint allowed */
|
||||
MaxSetpoint: number;
|
||||
MaxSetpoint?: number;
|
||||
/** Unique device identifier */
|
||||
Id: string;
|
||||
/** Optional zone assignment for the device */
|
||||
|
||||
@@ -13,43 +13,45 @@ export interface DeviceState {
|
||||
/** Overall timestamp for the device state */
|
||||
Timestamp: number;
|
||||
/** Time the device has been on */
|
||||
OnTime: TimestampedValue<number>;
|
||||
OnTime?: TimestampedValue<number>;
|
||||
/** Temperature set point */
|
||||
SetPoint: TimestampedValue<number>;
|
||||
SetPoint?: TimestampedValue<number>;
|
||||
/** Display brightness level */
|
||||
Brightness: TimestampedValue<number>;
|
||||
Brightness?: TimestampedValue<number>;
|
||||
/** Schedule mode setting */
|
||||
ScheduleMode: TimestampedValue<number>;
|
||||
ScheduleMode?: TimestampedValue<number>;
|
||||
/** Hold time setting */
|
||||
HoldTime: TimestampedValue<number>;
|
||||
HoldTime?: TimestampedValue<number>;
|
||||
/** Wi-Fi signal strength */
|
||||
Rssi: TimestampedValue<number>;
|
||||
Rssi?: TimestampedValue<number>;
|
||||
/** Thermostat mode */
|
||||
TstatMode: TimestampedValue<number>;
|
||||
TstatMode?: TimestampedValue<number>;
|
||||
/** Available heap memory */
|
||||
FreeHeap: TimestampedValue<number>;
|
||||
FreeHeap?: TimestampedValue<number>;
|
||||
/** Sensor temperature reading */
|
||||
SensorTemp: TimestampedValue<number>;
|
||||
SensorTemp?: TimestampedValue<number>;
|
||||
/** Current mode */
|
||||
Mode: TimestampedValue<number>;
|
||||
Mode?: TimestampedValue<number>;
|
||||
/** Voltage measurement */
|
||||
Voltage: TimestampedValue<number>;
|
||||
Voltage?: TimestampedValue<number>;
|
||||
/** Temperature corrected for calibration */
|
||||
CorrectedTemp: TimestampedValue<number>;
|
||||
CorrectedTemp?: TimestampedValue<number>;
|
||||
/** Duty cycle percentage */
|
||||
Duty: TimestampedValue<number>;
|
||||
Duty?: TimestampedValue<number>;
|
||||
/** Heat sink temperature */
|
||||
HeatSink: TimestampedValue<number>;
|
||||
HeatSink?: TimestampedValue<number>;
|
||||
/** Time the device has been off */
|
||||
OffTime: TimestampedValue<number>;
|
||||
OffTime?: TimestampedValue<number>;
|
||||
/** Connection status */
|
||||
Connected: TimestampedValue<boolean>;
|
||||
Connected?: TimestampedValue<boolean>;
|
||||
/** Current consumption */
|
||||
Current: TimestampedValue<number>;
|
||||
Current?: TimestampedValue<number>;
|
||||
/** Humidity reading */
|
||||
Humidity: TimestampedValue<number>;
|
||||
Humidity?: TimestampedValue<number>;
|
||||
/** Lock status */
|
||||
Lock: TimestampedValue<number>;
|
||||
Lock?: TimestampedValue<number>;
|
||||
/** Fan speed */
|
||||
FanSpeed?: TimestampedValue<number>;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user