15 Commits

Author SHA1 Message Date
Pascal Bourque
131f8677d9 fix: DayJS 'duration' import breaks ESM consumers (#15) 2025-06-05 16:32:14 -04:00
dependabot[bot]
ba5d29379a chore(deps): Bump aws-iot-device-sdk-v2 from 1.21.4 to 1.21.5 (#11) 2025-06-05 12:15:07 +00:00
dependabot[bot]
0dfb486ea1 chore(deps-dev): Bump typescript-eslint from 8.33.0 to 8.33.1 (#12) 2025-06-05 12:12:11 +00:00
dependabot[bot]
2c483a835d chore(deps): Bump @aws-sdk/credential-providers from 3.821.0 to 3.823.0 (#13) 2025-06-05 12:11:58 +00:00
Pascal Bourque
7f89e9867a fix(logging): Reduced the log level of session-related logs (#14) 2025-06-05 08:11:37 -04:00
Pascal Bourque
6b4e41828a feat: Added getDeviceStates API 2025-06-02 07:25:04 -04:00
dependabot[bot]
be940daf91 chore(deps-dev): Bump the dev-dependencies group with 3 updates (#8) 2025-06-02 11:09:46 +00:00
dependabot[bot]
847b9abf5e chore(deps): Bump @aws-sdk/credential-providers from 3.817.0 to 3.821.0 (#7) 2025-06-02 11:06:16 +00:00
dependabot[bot]
17d7e9b7b0 chore(deps-dev): Bump @eslint/js from 9.27.0 to 9.28.0 (#9) 2025-06-02 11:05:16 +00:00
Pascal Bourque
9df5030228 feat: Added getDeviceFirmwares API (#10) 2025-06-02 07:04:45 -04:00
dependabot[bot]
5ae54dd05d chore(deps-dev): Bump typedoc from 0.28.4 to 0.28.5 (#4) 2025-05-31 13:54:45 +00:00
dependabot[bot]
4039f5f165 chore(deps-dev): Bump @types/node from 22.15.21 to 22.15.23 in the dev-dependencies group (#5) 2025-05-31 13:52:37 +00:00
dependabot[bot]
45ae56f0f9 chore(deps-dev): Bump typescript-eslint from 8.32.1 to 8.33.0 (#6) 2025-05-31 13:52:20 +00:00
Pascal Bourque
aaac9f6d73 fix: Export all types modules (#3) 2025-05-25 17:59:25 -04:00
Pascal Bourque
43ac8334f0 ci: Configured Dependabot to use chore commit prefix 2025-05-25 11:29:56 -04:00
13 changed files with 775 additions and 562 deletions

View File

@@ -11,6 +11,9 @@ updates:
interval: 'daily' interval: 'daily'
labels: labels:
- 'dependencies' - 'dependencies'
commit-message:
prefix: 'chore'
include: 'scope'
groups: groups:
dev-dependencies: dev-dependencies:
patterns: patterns:

View File

@@ -1,5 +1,4 @@
import { MysaApiClient } from '@/api/MysaApiClient'; import { MysaApiClient, MysaSession } from '@/api';
import { MysaSession } from '@/api/MysaSession';
import 'dotenv/config'; import 'dotenv/config';
import { readFile, rm, writeFile } from 'fs/promises'; import { readFile, rm, writeFile } from 'fs/promises';
import { pino } from 'pino'; import { pino } from 'pino';
@@ -93,4 +92,6 @@ async function main() {
} }
} }
main().catch(rootLogger.error); main().catch((error) => {
rootLogger.error(error, 'Error in main');
});

1141
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -46,21 +46,21 @@
"build:docs": "typedoc" "build:docs": "typedoc"
}, },
"dependencies": { "dependencies": {
"@aws-sdk/credential-providers": "3.817.0", "@aws-sdk/credential-providers": "3.823.0",
"amazon-cognito-identity-js": "6.3.15", "amazon-cognito-identity-js": "6.3.15",
"aws-iot-device-sdk-v2": "1.21.4", "aws-iot-device-sdk-v2": "1.21.5",
"dayjs": "1.11.13", "dayjs": "1.11.13",
"lodash": "4.17.21" "lodash": "4.17.21"
}, },
"devDependencies": { "devDependencies": {
"@eslint/js": "9.27.0", "@eslint/js": "9.28.0",
"@semantic-release/npm": "12.0.1", "@semantic-release/npm": "12.0.1",
"@types/lodash": "4.17.17", "@types/lodash": "4.17.17",
"@types/node": "22.15.21", "@types/node": "22.15.29",
"conventional-changelog-conventionalcommits": "9.0.0", "conventional-changelog-conventionalcommits": "9.0.0",
"dotenv": "16.5.0", "dotenv": "16.5.0",
"eslint": "9.27.0", "eslint": "9.28.0",
"eslint-plugin-jsdoc": "50.6.17", "eslint-plugin-jsdoc": "50.7.1",
"eslint-plugin-tsdoc": "0.4.0", "eslint-plugin-tsdoc": "0.4.0",
"pino": "9.7.0", "pino": "9.7.0",
"pino-pretty": "13.0.0", "pino-pretty": "13.0.0",
@@ -70,9 +70,9 @@
"semantic-release": "24.2.5", "semantic-release": "24.2.5",
"tsup": "8.5.0", "tsup": "8.5.0",
"tsx": "4.19.4", "tsx": "4.19.4",
"typedoc": "0.28.4", "typedoc": "0.28.5",
"typedoc-material-theme": "1.4.0", "typedoc-material-theme": "1.4.0",
"typescript": "5.8.3", "typescript": "5.8.3",
"typescript-eslint": "8.32.1" "typescript-eslint": "8.33.1"
} }
} }

View File

@@ -6,7 +6,7 @@ import { ChangeDeviceState } from '@/types/mqtt/in/ChangeDeviceState';
import { InMessageType } from '@/types/mqtt/in/InMessageType'; import { InMessageType } from '@/types/mqtt/in/InMessageType';
import { StartPublishingDeviceStatus } from '@/types/mqtt/in/StartPublishingDeviceStatus'; import { StartPublishingDeviceStatus } from '@/types/mqtt/in/StartPublishingDeviceStatus';
import { OutMessageType } from '@/types/mqtt/out/OutMessageType'; import { OutMessageType } from '@/types/mqtt/out/OutMessageType';
import { Devices } from '@/types/rest/Devices'; import { Devices, DeviceStates, Firmwares } from '@/types/rest';
import { fromCognitoIdentityPool } from '@aws-sdk/credential-providers'; import { fromCognitoIdentityPool } from '@aws-sdk/credential-providers';
import { import {
AuthenticationDetails, AuthenticationDetails,
@@ -19,7 +19,7 @@ import {
} from 'amazon-cognito-identity-js'; } from 'amazon-cognito-identity-js';
import { iot, mqtt } from 'aws-iot-device-sdk-v2'; import { iot, mqtt } from 'aws-iot-device-sdk-v2';
import dayjs from 'dayjs'; import dayjs from 'dayjs';
import duration from 'dayjs/plugin/duration'; import duration from 'dayjs/plugin/duration.js';
import { MysaApiError, UnauthenticatedError } from './Errors'; import { MysaApiError, UnauthenticatedError } from './Errors';
import { Logger, VoidLogger } from './Logger'; import { Logger, VoidLogger } from './Logger';
import { MysaApiClientEventTypes } from './MysaApiClientEventTypes'; import { MysaApiClientEventTypes } from './MysaApiClientEventTypes';
@@ -184,7 +184,43 @@ export class MysaApiClient {
const response = await this._fetcher(`${MysaApiBaseUrl}/devices`, { const response = await this._fetcher(`${MysaApiBaseUrl}/devices`, {
headers: { headers: {
Authorization: `${session.getAccessToken().getJwtToken()}` Authorization: `${session.getIdToken().getJwtToken()}`
}
});
if (!response.ok) {
throw new MysaApiError(response);
}
return response.json();
}
async getDeviceFirmwares(): Promise<Firmwares> {
this._logger.debug(`Fetching device firmwares...`);
const session = await this.getFreshSession();
const response = await this._fetcher(`${MysaApiBaseUrl}/devices/firmware`, {
headers: {
Authorization: `${session.getIdToken().getJwtToken()}`
}
});
if (!response.ok) {
throw new MysaApiError(response);
}
return response.json();
}
async getDeviceStates(): Promise<DeviceStates> {
this._logger.debug(`Fetching device states...`);
const session = await this.getFreshSession();
const response = await this._fetcher(`${MysaApiBaseUrl}/devices/state`, {
headers: {
Authorization: `${session.getIdToken().getJwtToken()}`
} }
}); });
@@ -252,10 +288,10 @@ export class MysaApiClient {
* @param deviceId - The ID of the device to start receiving updates for. * @param deviceId - The ID of the device to start receiving updates for.
*/ */
async startRealtimeUpdates(deviceId: string) { 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)) { 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; return;
} }
@@ -296,6 +332,8 @@ export class MysaApiClient {
* @param deviceId - The ID of the device to stop receiving real-time updates for. * @param deviceId - The ID of the device to stop receiving real-time updates for.
*/ */
async stopRealtimeUpdates(deviceId: string) { async stopRealtimeUpdates(deviceId: string) {
this._logger.info(`Stopping real-time updates for device '${deviceId}'`);
const timer = this._realtimeDeviceIds.get(deviceId); const timer = this._realtimeDeviceIds.get(deviceId);
if (!timer) { if (!timer) {
this._logger.warn(`No real-time updates are running for device '${deviceId}'`); this._logger.warn(`No real-time updates are running for device '${deviceId}'`);
@@ -308,7 +346,6 @@ export class MysaApiClient {
this._logger.debug(`Unsubscribing to MQTT topic '/v1/dev/${deviceId}/out'...`); this._logger.debug(`Unsubscribing to MQTT topic '/v1/dev/${deviceId}/out'...`);
await mqttConnection.unsubscribe(`/v1/dev/${deviceId}/out`); await mqttConnection.unsubscribe(`/v1/dev/${deviceId}/out`);
this._logger.debug(`Stopping real-time updates for device '${deviceId}'...`);
clearInterval(timer); clearInterval(timer);
this._realtimeDeviceIds.delete(deviceId); this._realtimeDeviceIds.delete(deviceId);
} }
@@ -320,20 +357,20 @@ export class MysaApiClient {
if ( if (
this._cognitoUserSession.isValid() && this._cognitoUserSession.isValid() &&
dayjs.unix(this._cognitoUserSession.getAccessToken().getExpiration()).isAfter() 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); 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) => { return new Promise<CognitoUserSession>((resolve, reject) => {
this._cognitoUser!.refreshSession(this._cognitoUserSession!.getRefreshToken(), (error, session) => { this._cognitoUser!.refreshSession(this._cognitoUserSession!.getRefreshToken(), (error, session) => {
if (error) { if (error) {
this._logger.error('Failed to refresh session:', error); this._logger.error('Failed to refresh session:', error);
reject(new UnauthenticatedError('Unable to refresh the authentication session.')); reject(new UnauthenticatedError('Unable to refresh the authentication session.'));
} else { } else {
this._logger.info('Session refreshed successfully'); this._logger.debug('Session refreshed successfully');
this._cognitoUserSession = session; this._cognitoUserSession = session;
this.emitter.emit('sessionChanged', this.session); this.emitter.emit('sessionChanged', this.session);
resolve(session); resolve(session);

View File

@@ -1 +1,2 @@
export * from './api'; export * from './api';
export * from './types';

2
src/types/index.ts Normal file
View File

@@ -0,0 +1,2 @@
export * from './mqtt';
export * from './rest';

View File

@@ -0,0 +1,4 @@
export * from './ChangeDeviceState';
export * from './CheckDeviceSettings';
export * from './InMessageType';
export * from './StartPublishingDeviceStatus';

10
src/types/mqtt/index.ts Normal file
View File

@@ -0,0 +1,10 @@
export * from './in';
export * from './InPayload';
export * from './MsgBasePayload';
export * from './MsgInPayload';
export * from './MsgOutPayload';
export * from './MsgTypeBasePayload';
export * from './MsgTypeInPayload';
export * from './MsgTypeOutPayload';
export * from './out';
export * from './OutPayload';

View File

@@ -0,0 +1,7 @@
export * from './DeviceLog';
export * from './DevicePostBoot';
export * from './DeviceSetpointChange';
export * from './DeviceStateChange';
export * from './DeviceV1Status';
export * from './DeviceV2Status';
export * from './OutMessageType';

View File

@@ -0,0 +1,17 @@
/** Device firmware information */
export interface FirmwareDevice {
/** Device ID */
Device: string;
/** Device firmware version */
InstalledVersion: string;
}
/**
* Collection of firmware devices indexed by device ID
*
* Maps device ID strings to their corresponding firmware device objects, providing a lookup table for all devices
* associated with a user account.
*/
export interface Firmwares {
Firmware: Record<string, FirmwareDevice>;
}

69
src/types/rest/States.ts Normal file
View File

@@ -0,0 +1,69 @@
/** Represents a timestamped value with metadata */
export interface TimestampedValue<T = number> {
/** Timestamp when the value was recorded */
t: number;
/** The actual value */
v: T;
}
/** Represents the state of a single device */
export interface DeviceState {
/** Device identifier */
Device: string;
/** Overall timestamp for the device state */
Timestamp: number;
/** Time the device has been on */
OnTime: TimestampedValue<number>;
/** Temperature set point */
SetPoint: TimestampedValue<number>;
/** Display brightness level */
Brightness: TimestampedValue<number>;
/** Schedule mode setting */
ScheduleMode: TimestampedValue<number>;
/** Hold time setting */
HoldTime: TimestampedValue<number>;
/** Wi-Fi signal strength */
Rssi: TimestampedValue<number>;
/** Thermostat mode */
TstatMode: TimestampedValue<number>;
/** Available heap memory */
FreeHeap: TimestampedValue<number>;
/** Sensor temperature reading */
SensorTemp: TimestampedValue<number>;
/** Current mode */
Mode: TimestampedValue<number>;
/** Voltage measurement */
Voltage: TimestampedValue<number>;
/** Temperature corrected for calibration */
CorrectedTemp: TimestampedValue<number>;
/** Duty cycle percentage */
Duty: TimestampedValue<number>;
/** Heat sink temperature */
HeatSink: TimestampedValue<number>;
/** Time the device has been off */
OffTime: TimestampedValue<number>;
/** Connection status */
Connected: TimestampedValue<boolean>;
/** Current consumption */
Current: TimestampedValue<number>;
/** Humidity reading */
Humidity: TimestampedValue<number>;
/** Lock status */
Lock: TimestampedValue<number>;
}
/**
* Collection of device states indexed by device ID
*
* Maps device ID strings to their corresponding device state objects, providing a lookup table for all devices
* associated with a user account.
*/
export interface DeviceStatesObj {
/** Device state objects indexed by their unique device ID strings */
[deviceId: string]: DeviceState;
}
/** Top-level interface for the device states REST API response. */
export interface DeviceStates {
DeviceStatesObj: DeviceStatesObj;
}

3
src/types/rest/index.ts Normal file
View File

@@ -0,0 +1,3 @@
export * from './Devices';
export * from './Firmwares';
export * from './States';