mirror of
https://github.com/bourquep/mysa-js-sdk.git
synced 2026-02-04 09:41:07 +00:00
Compare commits
32 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
98003665b8 | ||
|
|
7afec1a7a9 | ||
|
|
e6631b0fd8 | ||
|
|
efaf3310d2 | ||
|
|
a62b538c42 | ||
|
|
2023e8b321 | ||
|
|
808e8f1037 | ||
|
|
f201c7944a | ||
|
|
f6c6127dab | ||
|
|
73cec9a90e | ||
|
|
39fc9048df | ||
|
|
45d69453df | ||
|
|
6dc6da2dde | ||
|
|
0cf7a1756c | ||
|
|
51b8f64dab | ||
|
|
14ee1d30eb | ||
|
|
4680ca2f85 | ||
|
|
3f020d5dc3 | ||
|
|
e93741525c | ||
|
|
9b945869aa | ||
|
|
becafbfacc | ||
|
|
c29e750f9c | ||
|
|
e3c93453ed | ||
|
|
17f277e844 | ||
|
|
6a88e52702 | ||
|
|
d6971453d2 | ||
|
|
8769928622 | ||
|
|
131f8677d9 | ||
|
|
ba5d29379a | ||
|
|
0dfb486ea1 | ||
|
|
2c483a835d | ||
|
|
7f89e9867a |
@@ -51,6 +51,12 @@ Then, run the example:
|
||||
npm run example
|
||||
```
|
||||
|
||||
If you prefer to see the raw data published by your Mysa smart thermostats, run:
|
||||
|
||||
```bash
|
||||
npm run example:raw
|
||||
```
|
||||
|
||||
## Using
|
||||
|
||||
The Mysa SDK provides a simple interface to interact with Mysa smart thermostats.
|
||||
|
||||
@@ -57,37 +57,46 @@ async function main() {
|
||||
|
||||
const devices = await client.getDevices();
|
||||
|
||||
client.emitter.on('statusChanged', (status) => {
|
||||
try {
|
||||
const device = devices.DevicesObj[status.deviceId];
|
||||
const watts = status.current !== undefined ? status.current * device.Voltage : undefined;
|
||||
rootLogger.info(
|
||||
`'${device.Name}' status changed: ${status.temperature}°C, ${status.humidity}%, ${watts ?? 'na'}W`
|
||||
);
|
||||
} catch (error) {
|
||||
rootLogger.error(`Error processing status update for device '${status.deviceId}':`, error);
|
||||
}
|
||||
});
|
||||
if (process.env.MYSA_OUTPUT_RAW_DATA === 'true') {
|
||||
client.emitter.on('rawRealtimeMessageReceived', (data) => {
|
||||
rootLogger.info(data, 'Raw message received');
|
||||
});
|
||||
} else {
|
||||
client.emitter.on('statusChanged', (status) => {
|
||||
try {
|
||||
const device = devices.DevicesObj[status.deviceId];
|
||||
const watts = status.current !== undefined ? status.current * device.Voltage : undefined;
|
||||
rootLogger.info(
|
||||
`'${device.Name}' status changed: ${status.temperature}°C, ${status.humidity}%, ${watts ?? 'na'}W`
|
||||
);
|
||||
} catch (error) {
|
||||
rootLogger.error(`Error processing status update for device '${status.deviceId}':`, error);
|
||||
}
|
||||
});
|
||||
|
||||
client.emitter.on('setPointChanged', (change) => {
|
||||
try {
|
||||
const device = devices.DevicesObj[change.deviceId];
|
||||
rootLogger.info(`'${device.Name}' setpoint changed from ${change.previousSetPoint} to ${change.newSetPoint}`);
|
||||
} catch (error) {
|
||||
rootLogger.error(`Error processing setpoint update for device '${change.deviceId}':`, error);
|
||||
}
|
||||
});
|
||||
client.emitter.on('setPointChanged', (change) => {
|
||||
try {
|
||||
const device = devices.DevicesObj[change.deviceId];
|
||||
rootLogger.info(`'${device.Name}' setpoint changed from ${change.previousSetPoint} to ${change.newSetPoint}`);
|
||||
} catch (error) {
|
||||
rootLogger.error(`Error processing setpoint update for device '${change.deviceId}':`, error);
|
||||
}
|
||||
});
|
||||
|
||||
client.emitter.on('stateChanged', (change) => {
|
||||
try {
|
||||
const device = devices.DevicesObj[change.deviceId];
|
||||
rootLogger.info(change, `'${device.Name}' state changed.`);
|
||||
} catch (error) {
|
||||
rootLogger.error(`Error processing setpoint update for device '${change.deviceId}':`, error);
|
||||
}
|
||||
});
|
||||
client.emitter.on('stateChanged', (change) => {
|
||||
try {
|
||||
const device = devices.DevicesObj[change.deviceId];
|
||||
rootLogger.info(change, `'${device.Name}' state changed.`);
|
||||
} catch (error) {
|
||||
rootLogger.error(`Error processing setpoint update for device '${change.deviceId}':`, error);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
for (const device of Object.entries(devices.DevicesObj)) {
|
||||
const serial = await client.getDeviceSerialNumber(device[0]);
|
||||
rootLogger.info(`Serial number for device '${device[0]}' (${device[1].Name}): ${serial}`);
|
||||
|
||||
await client.startRealtimeUpdates(device[0]);
|
||||
}
|
||||
}
|
||||
|
||||
2702
package-lock.json
generated
2702
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
39
package.json
39
package.json
@@ -40,39 +40,44 @@
|
||||
"browser": false,
|
||||
"scripts": {
|
||||
"example": "tsx --watch ./example/main.ts",
|
||||
"example:raw": "MYSA_OUTPUT_RAW_DATA=true tsx --watch ./example/main.ts",
|
||||
"lint": "eslint --max-warnings 0 src/**/*.ts",
|
||||
"style-lint": "prettier -c .",
|
||||
"build": "tsup",
|
||||
"build:docs": "typedoc"
|
||||
},
|
||||
"overrides": {
|
||||
"brace-expansion": "^2.0.2"
|
||||
},
|
||||
"dependencies": {
|
||||
"@aws-sdk/credential-providers": "3.821.0",
|
||||
"@aws-sdk/client-iot": "3.835.0",
|
||||
"@aws-sdk/credential-providers": "3.876.0",
|
||||
"amazon-cognito-identity-js": "6.3.15",
|
||||
"aws-iot-device-sdk-v2": "1.21.4",
|
||||
"aws-iot-device-sdk-v2": "1.22.0",
|
||||
"dayjs": "1.11.13",
|
||||
"lodash": "4.17.21"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "9.28.0",
|
||||
"@semantic-release/npm": "12.0.1",
|
||||
"@types/lodash": "4.17.17",
|
||||
"@types/node": "22.15.29",
|
||||
"@eslint/js": "9.34.0",
|
||||
"@semantic-release/npm": "12.0.2",
|
||||
"@types/lodash": "4.17.20",
|
||||
"@types/node": "24.3.0",
|
||||
"conventional-changelog-conventionalcommits": "9.0.0",
|
||||
"dotenv": "16.5.0",
|
||||
"eslint": "9.28.0",
|
||||
"eslint-plugin-jsdoc": "50.7.1",
|
||||
"dotenv": "17.2.1",
|
||||
"eslint": "9.34.0",
|
||||
"eslint-plugin-jsdoc": "54.1.1",
|
||||
"eslint-plugin-tsdoc": "0.4.0",
|
||||
"pino": "9.7.0",
|
||||
"pino-pretty": "13.0.0",
|
||||
"prettier": "3.5.3",
|
||||
"prettier-plugin-jsdoc": "1.3.2",
|
||||
"prettier-plugin-organize-imports": "4.1.0",
|
||||
"semantic-release": "24.2.5",
|
||||
"prettier": "3.6.2",
|
||||
"prettier-plugin-jsdoc": "1.3.3",
|
||||
"prettier-plugin-organize-imports": "4.2.0",
|
||||
"semantic-release": "24.2.7",
|
||||
"tsup": "8.5.0",
|
||||
"tsx": "4.19.4",
|
||||
"typedoc": "0.28.5",
|
||||
"tsx": "4.20.3",
|
||||
"typedoc": "0.28.11",
|
||||
"typedoc-material-theme": "1.4.0",
|
||||
"typescript": "5.8.3",
|
||||
"typescript-eslint": "8.33.0"
|
||||
"typescript": "5.9.2",
|
||||
"typescript-eslint": "8.41.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import { InMessageType } from '@/types/mqtt/in/InMessageType';
|
||||
import { StartPublishingDeviceStatus } from '@/types/mqtt/in/StartPublishingDeviceStatus';
|
||||
import { OutMessageType } from '@/types/mqtt/out/OutMessageType';
|
||||
import { Devices, DeviceStates, Firmwares } from '@/types/rest';
|
||||
import { DescribeThingCommand, IoTClient } from '@aws-sdk/client-iot';
|
||||
import { fromCognitoIdentityPool } from '@aws-sdk/credential-providers';
|
||||
import {
|
||||
AuthenticationDetails,
|
||||
@@ -19,7 +20,7 @@ import {
|
||||
} from 'amazon-cognito-identity-js';
|
||||
import { iot, mqtt } from 'aws-iot-device-sdk-v2';
|
||||
import dayjs from 'dayjs';
|
||||
import duration from 'dayjs/plugin/duration';
|
||||
import duration from 'dayjs/plugin/duration.js';
|
||||
import { MysaApiError, UnauthenticatedError } from './Errors';
|
||||
import { Logger, VoidLogger } from './Logger';
|
||||
import { MysaApiClientEventTypes } from './MysaApiClientEventTypes';
|
||||
@@ -143,8 +144,23 @@ export class MysaApiClient {
|
||||
/**
|
||||
* Logs in the user with the given email address and password.
|
||||
*
|
||||
* This method authenticates the user with Mysa's Cognito user pool and establishes a session that can be used for
|
||||
* subsequent API calls. Upon successful login, a 'sessionChanged' event is emitted.
|
||||
*
|
||||
* @example
|
||||
*
|
||||
* ```typescript
|
||||
* try {
|
||||
* await client.login('user@example.com', 'password123');
|
||||
* console.log('Login successful!');
|
||||
* } catch (error) {
|
||||
* console.error('Login failed:', error.message);
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param emailAddress - The email address of the user.
|
||||
* @param password - The password of the user.
|
||||
* @throws {@link Error} When authentication fails due to invalid credentials or network issues.
|
||||
*/
|
||||
async login(emailAddress: string, password: string): Promise<void> {
|
||||
this._cognitoUser = undefined;
|
||||
@@ -175,7 +191,21 @@ export class MysaApiClient {
|
||||
/**
|
||||
* Retrieves the list of devices associated with the user.
|
||||
*
|
||||
* This method fetches all Mysa devices linked to the authenticated user's account, including device information such
|
||||
* as models, locations, and configuration details.
|
||||
*
|
||||
* @example
|
||||
*
|
||||
* ```typescript
|
||||
* const devices = await client.getDevices();
|
||||
* for (const [deviceId, device] of Object.entries(devices.DevicesObj)) {
|
||||
* console.log(`Device: ${device.DisplayName} (${device.Model})`);
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @returns A promise that resolves to the list of devices.
|
||||
* @throws {@link MysaApiError} When the API request fails.
|
||||
* @throws {@link UnauthenticatedError} When the user is not authenticated.
|
||||
*/
|
||||
async getDevices(): Promise<Devices> {
|
||||
this._logger.debug(`Fetching devices...`);
|
||||
@@ -195,6 +225,70 @@ export class MysaApiClient {
|
||||
return response.json();
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the serial number for a specific device.
|
||||
*
|
||||
* This method uses AWS IoT's DescribeThing API to fetch the serial number attribute for the specified device. This
|
||||
* requires additional AWS IoT permissions and may not be available for all devices.
|
||||
*
|
||||
* @example
|
||||
*
|
||||
* ```typescript
|
||||
* const serialNumber = await client.getDeviceSerialNumber('device123');
|
||||
* if (serialNumber) {
|
||||
* console.log(`Device serial: ${serialNumber}`);
|
||||
* } else {
|
||||
* console.log('Serial number not available');
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* @param deviceId - The ID of the device to get the serial number for.
|
||||
* @returns A promise that resolves to the serial number, or undefined if not found.
|
||||
* @throws {@link UnauthenticatedError} When the user is not authenticated.
|
||||
*/
|
||||
async getDeviceSerialNumber(deviceId: string): Promise<string | undefined> {
|
||||
this._logger.debug(`Fetching serial number for device ${deviceId}...`);
|
||||
|
||||
const session = await this.getFreshSession();
|
||||
|
||||
// Get AWS credentials for IoT client
|
||||
const credentialsProvider = fromCognitoIdentityPool({
|
||||
clientConfig: {
|
||||
region: AwsRegion
|
||||
},
|
||||
identityPoolId: CognitoIdentityPoolId,
|
||||
logins: {
|
||||
[CognitoLoginKey]: session.getIdToken().getJwtToken()
|
||||
}
|
||||
});
|
||||
|
||||
const credentials = await credentialsProvider();
|
||||
const iotClient = new IoTClient({
|
||||
region: AwsRegion,
|
||||
credentials: {
|
||||
accessKeyId: credentials.accessKeyId,
|
||||
secretAccessKey: credentials.secretAccessKey,
|
||||
sessionToken: credentials.sessionToken
|
||||
}
|
||||
});
|
||||
|
||||
try {
|
||||
const command = new DescribeThingCommand({ thingName: deviceId });
|
||||
const response = await iotClient.send(command);
|
||||
return response.attributes?.['Serial'];
|
||||
} catch (error) {
|
||||
this._logger.warn(`Could not get serial number for device ${deviceId}:`, error);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves firmware information for all devices.
|
||||
*
|
||||
* @returns A promise that resolves to the firmware information for all devices.
|
||||
* @throws {@link MysaApiError} When the API request fails.
|
||||
* @throws {@link UnauthenticatedError} When the user is not authenticated.
|
||||
*/
|
||||
async getDeviceFirmwares(): Promise<Firmwares> {
|
||||
this._logger.debug(`Fetching device firmwares...`);
|
||||
|
||||
@@ -213,6 +307,13 @@ export class MysaApiClient {
|
||||
return response.json();
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the current state information for all devices.
|
||||
*
|
||||
* @returns A promise that resolves to the current state of all devices.
|
||||
* @throws {@link MysaApiError} When the API request fails.
|
||||
* @throws {@link UnauthenticatedError} When the user is not authenticated.
|
||||
*/
|
||||
async getDeviceStates(): Promise<DeviceStates> {
|
||||
this._logger.debug(`Fetching device states...`);
|
||||
|
||||
@@ -231,6 +332,31 @@ export class MysaApiClient {
|
||||
return response.json();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the state of a specific device by sending commands via MQTT.
|
||||
*
|
||||
* This method allows you to change the temperature set point and/or operating mode of a Mysa device. The command is
|
||||
* sent through the MQTT connection for real-time device control.
|
||||
*
|
||||
* @example
|
||||
*
|
||||
* ```typescript
|
||||
* // Set temperature to 22°C
|
||||
* await client.setDeviceState('device123', 22);
|
||||
*
|
||||
* // Turn device off
|
||||
* await client.setDeviceState('device123', undefined, 'off');
|
||||
*
|
||||
* // Set temperature and mode
|
||||
* await client.setDeviceState('device123', 20, 'heat');
|
||||
* ```
|
||||
*
|
||||
* @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).
|
||||
* @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) {
|
||||
this._logger.debug(`Setting device state for '${deviceId}'`);
|
||||
|
||||
@@ -285,13 +411,29 @@ export class MysaApiClient {
|
||||
/**
|
||||
* Starts receiving real-time updates for the specified device.
|
||||
*
|
||||
* This method establishes an MQTT subscription to receive live status updates from the device, including temperature,
|
||||
* humidity, set point changes, and other state information. The client will automatically send keep-alive messages to
|
||||
* maintain the connection.
|
||||
*
|
||||
* @example
|
||||
*
|
||||
* ```typescript
|
||||
* // Start receiving updates and listen for events
|
||||
* await client.startRealtimeUpdates('device123');
|
||||
*
|
||||
* client.emitter.on('statusChanged', (status) => {
|
||||
* console.log(`Temperature: ${status.temperature}°C`);
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* @param deviceId - The ID of the device to start receiving updates for.
|
||||
* @throws {@link Error} When MQTT connection or subscription fails.
|
||||
*/
|
||||
async startRealtimeUpdates(deviceId: string) {
|
||||
this._logger.info(`Starting realtime updates for device '${deviceId}'`);
|
||||
this._logger.info(`Starting real-time updates for device '${deviceId}'`);
|
||||
|
||||
if (this._realtimeDeviceIds.has(deviceId)) {
|
||||
this._logger.debug(`Realtime updates for device '${deviceId}' already started`);
|
||||
this._logger.debug(`Real-time updates for device '${deviceId}' already started`);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -329,9 +471,15 @@ export class MysaApiClient {
|
||||
/**
|
||||
* Stops receiving real-time updates for the specified device.
|
||||
*
|
||||
* This method unsubscribes from the MQTT topic for the specified device and clears any associated timers to stop the
|
||||
* keep-alive messages.
|
||||
*
|
||||
* @param deviceId - The ID of the device to stop receiving real-time updates for.
|
||||
* @throws {@link Error} When MQTT unsubscription fails.
|
||||
*/
|
||||
async stopRealtimeUpdates(deviceId: string) {
|
||||
this._logger.info(`Stopping real-time updates for device '${deviceId}'`);
|
||||
|
||||
const timer = this._realtimeDeviceIds.get(deviceId);
|
||||
if (!timer) {
|
||||
this._logger.warn(`No real-time updates are running for device '${deviceId}'`);
|
||||
@@ -344,11 +492,19 @@ export class MysaApiClient {
|
||||
this._logger.debug(`Unsubscribing to MQTT topic '/v1/dev/${deviceId}/out'...`);
|
||||
await mqttConnection.unsubscribe(`/v1/dev/${deviceId}/out`);
|
||||
|
||||
this._logger.debug(`Stopping real-time updates for device '${deviceId}'...`);
|
||||
clearInterval(timer);
|
||||
this._realtimeDeviceIds.delete(deviceId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensures a valid, non-expired session is available.
|
||||
*
|
||||
* This method checks if the current session is valid and not expired. If the session is expired, it automatically
|
||||
* refreshes it using the refresh token.
|
||||
*
|
||||
* @returns A promise that resolves to a valid CognitoUserSession.
|
||||
* @throws {@link UnauthenticatedError} When no session exists or refresh fails.
|
||||
*/
|
||||
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.');
|
||||
@@ -358,18 +514,18 @@ export class MysaApiClient {
|
||||
this._cognitoUserSession.isValid() &&
|
||||
dayjs.unix(this._cognitoUserSession.getIdToken().getExpiration()).isAfter()
|
||||
) {
|
||||
this._logger.info('Session is valid, no need to refresh');
|
||||
this._logger.debug('Session is valid, no need to refresh');
|
||||
return Promise.resolve(this._cognitoUserSession);
|
||||
}
|
||||
|
||||
this._logger.info('Session is not valid or expired, refreshing...');
|
||||
this._logger.debug('Session is not valid or expired, refreshing...');
|
||||
return new Promise<CognitoUserSession>((resolve, reject) => {
|
||||
this._cognitoUser!.refreshSession(this._cognitoUserSession!.getRefreshToken(), (error, session) => {
|
||||
if (error) {
|
||||
this._logger.error('Failed to refresh session:', error);
|
||||
reject(new UnauthenticatedError('Unable to refresh the authentication session.'));
|
||||
} else {
|
||||
this._logger.info('Session refreshed successfully');
|
||||
this._logger.debug('Session refreshed successfully');
|
||||
this._cognitoUserSession = session;
|
||||
this.emitter.emit('sessionChanged', this.session);
|
||||
resolve(session);
|
||||
@@ -378,6 +534,15 @@ export class MysaApiClient {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Establishes and returns an MQTT connection for real-time communication.
|
||||
*
|
||||
* This method creates a new MQTT connection if one doesn't exist, using AWS IoT WebSocket connections with Cognito
|
||||
* credentials. The connection is cached and reused for subsequent calls.
|
||||
*
|
||||
* @returns A promise that resolves to an active MQTT connection.
|
||||
* @throws {@link Error} When connection establishment fails.
|
||||
*/
|
||||
private async getMqttConnection(): Promise<mqtt.MqttClientConnection> {
|
||||
if (this._mqttConnection) {
|
||||
return this._mqttConnection;
|
||||
@@ -419,6 +584,15 @@ export class MysaApiClient {
|
||||
return this._mqttConnection;
|
||||
}
|
||||
|
||||
/**
|
||||
* Processes incoming MQTT messages and emits appropriate events.
|
||||
*
|
||||
* This method parses MQTT payloads and converts them into typed events that can be listened to via the client's event
|
||||
* emitter. It handles both v1 and v2 device message formats and emits events like 'statusChanged', 'setPointChanged',
|
||||
* and 'stateChanged'.
|
||||
*
|
||||
* @param payload - The raw MQTT message payload to process.
|
||||
*/
|
||||
private processMqttMessage(payload: ArrayBuffer) {
|
||||
try {
|
||||
const parsedPayload = parseMqttPayload(payload);
|
||||
|
||||
@@ -32,7 +32,7 @@ export function parseMqttPayload(payload: ArrayBuffer): OutPayload {
|
||||
* @param payload - The typed payload object to serialize
|
||||
* @returns The serialized payload as ArrayBuffer ready for MQTT transmission
|
||||
*/
|
||||
export function serializeMqttPayload<T extends InPayload>(payload: T): ArrayBuffer {
|
||||
export function serializeMqttPayload<T extends InPayload>(payload: T): Uint8Array<ArrayBuffer> {
|
||||
const jsonString = JSON.stringify(payload);
|
||||
const encoder = new TextEncoder();
|
||||
return encoder.encode(jsonString);
|
||||
|
||||
Reference in New Issue
Block a user