initial release of Alex2Node

This commit is contained in:
David 2025-04-20 21:19:57 +00:00
parent 0804bd7397
commit 4eb2a84d72
20 changed files with 2047 additions and 3 deletions

41
src/ActionMapping.ts Normal file
View file

@ -0,0 +1,41 @@
export enum AlexaActions {
Open = "Alexa.Actions.Open",
Close = "Alexa.Actions.Close",
Raise = "Alexa.Actions.Raise",
Lower = "Alexa.Actions.Lower",
SetEcoOn = "Alexa.Actions.SetEcoOn",
SetEcoOff = "Alexa.Actions.SetEcoOff",
}
interface Directive {
name: string;
payload?: string;
}
export class ActionMapping {
type: string = "ActionsToDirective";
actions: AlexaActions[];
directive: Directive;
constructor(
actions: AlexaActions[],
directiveName: string,
directivePayload: string | undefined
) {
this.actions = actions;
this.directive = {
name: directiveName,
};
if (directivePayload) {
this.directive.payload = directivePayload;
}
}
toJSON(): object {
return {
"@type": this.type,
actions: this.actions,
directive: this.directive,
};
}
}

131
src/Alex2Node.ts Normal file
View file

@ -0,0 +1,131 @@
import mqtt, { MqttClient } from "mqtt";
import Device from "./Device";
class Alex2MQTT {
private client: MqttClient | null = null;
private devices: Device[] = [];
private MqttHost = "mqtt://Alex2MQTT.stormysdream.club";
constructor(
private username: string,
private password: string,
private rootTopic: string,
private debugLogging: boolean
) {}
connect(): void {
const options = {
username: this.username,
password: this.password,
};
this.client = mqtt.connect(this.MqttHost, options);
this.client.on("connect", () => {
if (this.debugLogging) {
console.log("[Alex2Node.ts] Connected to MQTT broker");
}
this.client!.subscribe(this.rootTopic + "/#", (err) => {
if (this.debugLogging && !err) {
console.log("[Alex2Node.ts] Subscribed to topics");
}
if (err) {
throw err;
}
});
});
this.client.on("message", (topic: string, message: Buffer) => {
if (this.debugLogging) {
console.log(`[Alex2Node.ts] MQTT Message Received`);
console.log(` Topic: ${topic}`);
console.log(` Payload: ${message.toString()}`);
}
if (topic == `${this.rootTopic}/discover`) {
if (this.debugLogging) {
console.log(
"[Alex2Node.ts] Discovery request received, getting device json..."
);
}
const deviceArray = this.devices.map((device) => device.getJSON());
if (deviceArray.length > 0) {
this.client!.publish(
topic + "_r",
JSON.stringify(deviceArray),
(err) => {
if (err) {
throw err;
} else if (this.debugLogging) {
console.log(
`[Alex2Node.ts] Discovery payloads published to ${
topic + "_r"
}`
);
console.log(deviceArray);
}
}
);
}
} else if (topic.split("/").length == 3) {
const [root, endpointId, directiveType] = topic.split("/");
if (directiveType != "alexaDirective") {
return;
}
const device = this.devices.find((d) => d.endpointId === endpointId);
if (!device) {
if (this.debugLogging) {
console.warn(
`[Alex2Node.ts] No device found for endpointId: ${endpointId}`
);
}
return;
}
let payload;
try {
payload = JSON.parse(message.toString());
} catch (e) {
console.error(`[Alex2Node.ts] Failed to parse payload JSON`, e);
return;
}
if (
payload.header &&
payload.header.namespace === "Alexa" &&
payload.header.name === "ReportState"
) {
if (this.debugLogging) {
console.log(
`[Alex2Node.ts] ReportState directive for device ${endpointId}`
);
}
device.emit("ReportState", payload);
}else{
device.emit("Event", payload,payload.header.namespace);
}
}
});
this.client.on("error", (err: Error) => {
if (this.debugLogging) {
console.error("[Alex2Node.ts] Connection failed:", err);
}
throw err;
});
}
registerDevice(name: string, endpointId: string): Device {
if (!this.client) {
throw new Error("Must call connect before creating devices");
}
if (this.debugLogging) {
console.log(
`[Alex2Node.ts] Creating new device with endpoint: ${endpointId}`
);
}
const device = new Device(this.client!, this.rootTopic, name, endpointId);
this.devices.push(device);
return device;
}
}
export default Alex2MQTT;

307
src/AlexaInterface.ts Normal file
View file

@ -0,0 +1,307 @@
import { ActionMapping, AlexaActions } from "./ActionMapping";
export enum AlexaInterfaceType {
APPLICATION_STATE_REPORTER = "Alexa.ApplicationStateReporter",
AUDIO_PLAY_QUEUE = "Alexa.Audio.PlayQueue",
AUTHORIZATION_CONTROLLER = "Alexa.AuthorizationController",
AUTOMATION_MANAGEMENT = "Alexa.AutomationManagement",
AUTOMOTIVE_VEHICLE_DATA = "Alexa.Automotive.VehicleData",
BRIGHTNESS_CONTROLLER = "Alexa.BrightnessController",
CAMERA_LIVE_VIEW_CONTROLLER = "Alexa.Camera.LiveViewController",
CAMERA_STREAM_CONTROLLER = "Alexa.CameraStreamController",
CHANNEL_CONTROLLER = "Alexa.ChannelController",
COLOR_CONTROLLER = "Alexa.ColorController",
COLOR_TEMPERATURE_CONTROLLER = "Alexa.ColorTemperatureController",
COMMISSIONABLE = "Alexa.Commissionable",
CONSENT_MANAGEMENT_CONSENT_REQUIRED_REPORTER = "Alexa.ConsentManagement.ConsentRequiredReporter",
CONTACT_SENSOR = "Alexa.ContactSensor",
COOKING = "Alexa.Cooking",
COOKING_FOOD_TEMPERATURE_CONTROLLER = "Alexa.Cooking.FoodTemperatureController",
COOKING_FOOD_TEMPERATURE_SENSOR = "Alexa.Cooking.FoodTemperatureSensor",
COOKING_PRESET_CONTROLLER = "Alexa.Cooking.PresetController",
COOKING_TEMPERATURE_CONTROLLER = "Alexa.Cooking.TemperatureController",
COOKING_TEMPERATURE_SENSOR = "Alexa.Cooking.TemperatureSensor",
COOKING_TIME_CONTROLLER = "Alexa.Cooking.TimeController",
DATA_CONTROLLER = "Alexa.DataController",
DEVICE_USAGE_ESTIMATION = "Alexa.DeviceUsage.Estimation",
DEVICE_USAGE_METER = "Alexa.DeviceUsage.Meter",
DOORBELL_EVENT_SOURCE = "Alexa.DoorbellEventSource",
ENDPOINT_HEALTH = "Alexa.EndpointHealth",
EQUALIZER_CONTROLLER = "Alexa.EqualizerController",
INPUT_CONTROLLER = "Alexa.InputController",
INVENTORY_LEVEL_SENSOR = "Alexa.InventoryLevelSensor",
INVENTORY_LEVEL_USAGE_SENSOR = "Alexa.InventoryLevelUsageSensor",
INVENTORY_USAGE_SENSOR = "Alexa.InventoryUsageSensor",
KEYPAD_CONTROLLER = "Alexa.KeypadController",
LAUNCHER = "Alexa.Launcher",
LOCK_CONTROLLER = "Alexa.LockController",
MEDIA_PLAYBACK = "Alexa.Media.Playback",
MEDIA_PLAY_QUEUE = "Alexa.Media.PlayQueue",
MEDIA_SEARCH = "Alexa.Media.Search",
MODE_CONTROLLER = "Alexa.ModeController",
MOTION_SENSOR = "Alexa.MotionSensor",
PERCENTAGE_CONTROLLER = "Alexa.PercentageController",
PLAYBACK_CONTROLLER = "Alexa.PlaybackController",
PLAYBACK_STATE_REPORTER = "Alexa.PlaybackStateReporter",
POWER_CONTROLLER = "Alexa.PowerController",
POWER_LEVEL_CONTROLLER = "Alexa.PowerLevelController",
PROACTIVE_NOTIFICATION_SOURCE = "Alexa.ProactiveNotificationSource",
RANGE_CONTROLLER = "Alexa.RangeController",
RECORD_CONTROLLER = "Alexa.RecordController",
REMOTE_VIDEO_PLAYER = "Alexa.RemoteVideoPlayer",
RTC_SESSION_CONTROLLER = "Alexa.RTCSessionController",
SCENE_CONTROLLER = "Alexa.SceneController",
SECURITY_PANEL_CONTROLLER = "Alexa.SecurityPanelController",
SECURITY_PANEL_CONTROLLER_ALERT = "Alexa.SecurityPanelController.Alert",
SEEK_CONTROLLER = "Alexa.SeekController",
SIMPLE_EVENT_SOURCE = "Alexa.SimpleEventSource",
SMART_VISION_OBJECT_DETECTION_SENSOR = "Alexa.SmartVision.ObjectDetectionSensor",
SMART_VISION_SNAPSHOT_PROVIDER = "Alexa.SmartVision.SnapshotProvider",
SPEAKER = "Alexa.Speaker",
STEP_SPEAKER = "Alexa.StepSpeaker",
TEMPERATURE_SENSOR = "Alexa.TemperatureSensor",
THERMOSTAT_CONTROLLER = "Alexa.ThermostatController",
THERMOSTAT_CONTROLLER_CONFIGURATION = "Alexa.ThermostatController.Configuration",
THERMOSTAT_CONTROLLER_HVAC_COMPONENTS = "Alexa.ThermostatController.HVAC.Components",
THERMOSTAT_CONTROLLER_SCHEDULE = "Alexa.ThermostatController.Schedule",
TIME_HOLD_CONTROLLER = "Alexa.TimeHoldController",
TOGGLE_CONTROLLER = "Alexa.ToggleController",
UI_CONTROLLER = "Alexa.UIController",
USER_PREFERENCE = "Alexa.UserPreference",
VIDEO_RECORDER = "Alexa.VideoRecorder",
WAKE_ON_LAN_CONTROLLER = "Alexa.WakeOnLANController",
UNKNOWN = "UNKNOWN",
}
interface FriendlyName {
text: string;
locale: string;
}
export class AlexaInterface {
private friendlyNames: FriendlyName[] = [];
private actionMappings: ActionMapping[] = [];
constructor(
public type: AlexaInterfaceType,
public retrievable: boolean = true,
public proactivelyReported: boolean = false,
public instance = ""
) {}
addActionMapping(mapping: ActionMapping): void {
this.actionMappings.push(mapping);
}
addFriendlyName(name: string, locale: string): void {
this.friendlyNames.push({ text: name, locale });
}
setInstance(name: string): void {
this.instance = name;
}
getType(): AlexaInterfaceType {
return this.type;
}
getTypeString(): string {
return this.type;
}
getVersion(): string {
switch (this.type) {
case AlexaInterfaceType.APPLICATION_STATE_REPORTER:
case AlexaInterfaceType.AUDIO_PLAY_QUEUE:
case AlexaInterfaceType.AUTHORIZATION_CONTROLLER:
case AlexaInterfaceType.AUTOMATION_MANAGEMENT:
case AlexaInterfaceType.AUTOMOTIVE_VEHICLE_DATA:
case AlexaInterfaceType.COMMISSIONABLE:
case AlexaInterfaceType.CONSENT_MANAGEMENT_CONSENT_REQUIRED_REPORTER:
case AlexaInterfaceType.COOKING:
case AlexaInterfaceType.COOKING_FOOD_TEMPERATURE_CONTROLLER:
case AlexaInterfaceType.COOKING_FOOD_TEMPERATURE_SENSOR:
case AlexaInterfaceType.COOKING_PRESET_CONTROLLER:
case AlexaInterfaceType.COOKING_TEMPERATURE_CONTROLLER:
case AlexaInterfaceType.COOKING_TEMPERATURE_SENSOR:
case AlexaInterfaceType.COOKING_TIME_CONTROLLER:
case AlexaInterfaceType.DATA_CONTROLLER:
case AlexaInterfaceType.DEVICE_USAGE_ESTIMATION:
case AlexaInterfaceType.DEVICE_USAGE_METER:
case AlexaInterfaceType.EQUALIZER_CONTROLLER:
case AlexaInterfaceType.INVENTORY_LEVEL_SENSOR:
case AlexaInterfaceType.INVENTORY_LEVEL_USAGE_SENSOR:
case AlexaInterfaceType.INVENTORY_USAGE_SENSOR:
case AlexaInterfaceType.KEYPAD_CONTROLLER:
case AlexaInterfaceType.MEDIA_PLAYBACK:
case AlexaInterfaceType.MEDIA_PLAY_QUEUE:
case AlexaInterfaceType.MEDIA_SEARCH:
case AlexaInterfaceType.PLAYBACK_STATE_REPORTER:
case AlexaInterfaceType.PROACTIVE_NOTIFICATION_SOURCE:
case AlexaInterfaceType.REMOTE_VIDEO_PLAYER:
case AlexaInterfaceType.RTC_SESSION_CONTROLLER:
case AlexaInterfaceType.SECURITY_PANEL_CONTROLLER:
case AlexaInterfaceType.SECURITY_PANEL_CONTROLLER_ALERT:
case AlexaInterfaceType.SIMPLE_EVENT_SOURCE:
case AlexaInterfaceType.SMART_VISION_OBJECT_DETECTION_SENSOR:
case AlexaInterfaceType.SMART_VISION_SNAPSHOT_PROVIDER:
case AlexaInterfaceType.SPEAKER:
case AlexaInterfaceType.STEP_SPEAKER:
case AlexaInterfaceType.THERMOSTAT_CONTROLLER_CONFIGURATION:
case AlexaInterfaceType.THERMOSTAT_CONTROLLER_HVAC_COMPONENTS:
case AlexaInterfaceType.THERMOSTAT_CONTROLLER_SCHEDULE:
case AlexaInterfaceType.UI_CONTROLLER:
case AlexaInterfaceType.USER_PREFERENCE:
case AlexaInterfaceType.VIDEO_RECORDER:
case AlexaInterfaceType.WAKE_ON_LAN_CONTROLLER:
return "1";
case AlexaInterfaceType.BRIGHTNESS_CONTROLLER:
case AlexaInterfaceType.CAMERA_STREAM_CONTROLLER:
case AlexaInterfaceType.CHANNEL_CONTROLLER:
case AlexaInterfaceType.COLOR_CONTROLLER:
case AlexaInterfaceType.COLOR_TEMPERATURE_CONTROLLER:
case AlexaInterfaceType.CONTACT_SENSOR:
case AlexaInterfaceType.DOORBELL_EVENT_SOURCE:
case AlexaInterfaceType.INPUT_CONTROLLER:
case AlexaInterfaceType.LOCK_CONTROLLER:
case AlexaInterfaceType.MODE_CONTROLLER:
case AlexaInterfaceType.MOTION_SENSOR:
case AlexaInterfaceType.PERCENTAGE_CONTROLLER:
case AlexaInterfaceType.PLAYBACK_CONTROLLER:
case AlexaInterfaceType.POWER_CONTROLLER:
case AlexaInterfaceType.POWER_LEVEL_CONTROLLER:
case AlexaInterfaceType.RANGE_CONTROLLER:
case AlexaInterfaceType.RECORD_CONTROLLER:
case AlexaInterfaceType.SCENE_CONTROLLER:
case AlexaInterfaceType.SEEK_CONTROLLER:
case AlexaInterfaceType.TEMPERATURE_SENSOR:
case AlexaInterfaceType.THERMOSTAT_CONTROLLER:
case AlexaInterfaceType.TOGGLE_CONTROLLER:
return "3";
case AlexaInterfaceType.LAUNCHER:
return "1.1";
case AlexaInterfaceType.ENDPOINT_HEALTH:
return "3.3";
default:
return "UNKNOWN";
}
}
getProps(): string[] {
switch (this.type) {
case AlexaInterfaceType.AUTOMATION_MANAGEMENT:
return ["automationStatuses"];
case AlexaInterfaceType.BRIGHTNESS_CONTROLLER:
return ["brightness"];
case AlexaInterfaceType.CHANNEL_CONTROLLER:
return ["channel"];
case AlexaInterfaceType.COLOR_CONTROLLER:
return ["color"];
case AlexaInterfaceType.COLOR_TEMPERATURE_CONTROLLER:
return ["colorTemperatureInKelvin"];
case AlexaInterfaceType.CONTACT_SENSOR:
return ["detectionState"];
case AlexaInterfaceType.POWER_CONTROLLER:
return ["powerState"];
case AlexaInterfaceType.ENDPOINT_HEALTH:
return ["connectivity"];
case AlexaInterfaceType.TOGGLE_CONTROLLER:
return ["toggleState"];
case AlexaInterfaceType.TEMPERATURE_SENSOR:
return ["temperature"];
case AlexaInterfaceType.APPLICATION_STATE_REPORTER:
case AlexaInterfaceType.AUDIO_PLAY_QUEUE:
case AlexaInterfaceType.AUTHORIZATION_CONTROLLER:
case AlexaInterfaceType.AUTOMOTIVE_VEHICLE_DATA:
case AlexaInterfaceType.CAMERA_LIVE_VIEW_CONTROLLER:
case AlexaInterfaceType.CAMERA_STREAM_CONTROLLER:
case AlexaInterfaceType.COMMISSIONABLE:
case AlexaInterfaceType.CONSENT_MANAGEMENT_CONSENT_REQUIRED_REPORTER:
case AlexaInterfaceType.COOKING:
case AlexaInterfaceType.DATA_CONTROLLER:
case AlexaInterfaceType.DEVICE_USAGE_ESTIMATION:
case AlexaInterfaceType.DEVICE_USAGE_METER:
case AlexaInterfaceType.DOORBELL_EVENT_SOURCE:
case AlexaInterfaceType.EQUALIZER_CONTROLLER:
case AlexaInterfaceType.INPUT_CONTROLLER:
case AlexaInterfaceType.INVENTORY_LEVEL_SENSOR:
case AlexaInterfaceType.INVENTORY_LEVEL_USAGE_SENSOR:
case AlexaInterfaceType.INVENTORY_USAGE_SENSOR:
case AlexaInterfaceType.KEYPAD_CONTROLLER:
case AlexaInterfaceType.LAUNCHER:
case AlexaInterfaceType.LOCK_CONTROLLER:
case AlexaInterfaceType.MEDIA_PLAYBACK:
case AlexaInterfaceType.MEDIA_SEARCH:
case AlexaInterfaceType.MODE_CONTROLLER:
case AlexaInterfaceType.MOTION_SENSOR:
case AlexaInterfaceType.PERCENTAGE_CONTROLLER:
case AlexaInterfaceType.PLAYBACK_CONTROLLER:
case AlexaInterfaceType.PLAYBACK_STATE_REPORTER:
case AlexaInterfaceType.PROACTIVE_NOTIFICATION_SOURCE:
case AlexaInterfaceType.RANGE_CONTROLLER:
case AlexaInterfaceType.RECORD_CONTROLLER:
case AlexaInterfaceType.REMOTE_VIDEO_PLAYER:
case AlexaInterfaceType.RTC_SESSION_CONTROLLER:
case AlexaInterfaceType.SCENE_CONTROLLER:
case AlexaInterfaceType.SECURITY_PANEL_CONTROLLER:
case AlexaInterfaceType.SEEK_CONTROLLER:
case AlexaInterfaceType.SIMPLE_EVENT_SOURCE:
case AlexaInterfaceType.SMART_VISION_OBJECT_DETECTION_SENSOR:
case AlexaInterfaceType.SMART_VISION_SNAPSHOT_PROVIDER:
case AlexaInterfaceType.SPEAKER:
case AlexaInterfaceType.STEP_SPEAKER:
case AlexaInterfaceType.THERMOSTAT_CONTROLLER:
case AlexaInterfaceType.THERMOSTAT_CONTROLLER_CONFIGURATION:
case AlexaInterfaceType.THERMOSTAT_CONTROLLER_HVAC_COMPONENTS:
case AlexaInterfaceType.THERMOSTAT_CONTROLLER_SCHEDULE:
case AlexaInterfaceType.TIME_HOLD_CONTROLLER:
case AlexaInterfaceType.UI_CONTROLLER:
case AlexaInterfaceType.USER_PREFERENCE:
case AlexaInterfaceType.VIDEO_RECORDER:
case AlexaInterfaceType.WAKE_ON_LAN_CONTROLLER:
console.error("UNSUPORTED INTERFACE TYPE");
return [];
default:
return [];
}
}
getJSON(): object {
const doc: any = {
interface: this.getTypeString(),
version: this.getVersion(),
type: "AlexaInterface",
properties: {
retrievable: this.retrievable,
proactivelyReported: this.proactivelyReported,
supported: [{ name: this.getProps()[0] }],
},
};
if (this.instance) {
doc.instance = this.instance;
}
if (this.friendlyNames.length > 0) {
const capabilityResources = doc["capabilityResources"] || {};
const friendlyNamesArray = capabilityResources["friendlyNames"] || [];
this.friendlyNames.forEach((fn) => {
const friendlyNameObj: any = { "@type": "text" };
friendlyNameObj["value"] = {
text: fn.text,
locale: fn.locale,
};
friendlyNamesArray.push(friendlyNameObj);
});
doc["capabilityResources"] = capabilityResources;
}
if (this.actionMappings.length > 0) {
doc.semantics = {
actionMappings: this.actionMappings.map((am) => am.toJSON()),
};
}
return doc;
}
}

208
src/AlexaStatusMessage.ts Normal file
View file

@ -0,0 +1,208 @@
import { v4 as uuidv4 } from "uuid";
import { AlexaInterface, AlexaInterfaceType } from "./AlexaInterface";
import { MqttClient } from "mqtt";
export enum EndpointHealth {
OK = "OK",
UNREACHABLE = "UNREACHABLE",
}
export enum PowerController {
ON = "ON",
OFF = "OFF",
}
export enum TemperatureSensorScale {
CELSIUS = "CELSIUS",
FAHRENHEIT = "FAHRENHEIT",
}
interface DirectiveHeader {
namespace: string;
name: string;
payloadVersion: string;
messageId: string;
correlationToken: string;
}
interface DirectiveEndpoint {
endpointId: string;
}
interface ContextProperty {
namespace: string;
name: string;
value: any;
timeOfSample: string;
uncertaintyInMilliseconds: number;
instance?: string;
}
export class AlexaStatusMessage {
private context: { properties: ContextProperty[] } = { properties: [] };
private event: {
header: DirectiveHeader;
endpoint: DirectiveEndpoint;
payload: {};
};
private rootTopic: string;
private endpointId: string;
private mqttClient: MqttClient;
constructor(
correlationToken: string,
rootTopic: string,
endpointId: string,
mqttClient: MqttClient,
isResponse: boolean = false
) {
this.rootTopic = rootTopic;
this.endpointId = endpointId;
this.mqttClient = mqttClient;
this.event = {
header: {
namespace: "Alexa",
name: isResponse ? "Response" : "StateReport",
payloadVersion: "3",
messageId: this.generateMessageId(),
correlationToken,
},
endpoint: {
endpointId,
},
payload: {},
};
}
private generateMessageId(): string {
return uuidv4();
}
private getTimestamp(): string {
return new Date().toISOString();
}
private addProperty(
namespace: AlexaInterfaceType,
name: string,
value: any,
uncertaintyInMilliseconds = 0,
instance?: string
): this {
const prop: ContextProperty = {
namespace,
name,
value,
timeOfSample: this.getTimestamp(),
uncertaintyInMilliseconds,
};
if (instance) prop.instance = instance;
this.context.properties.push(prop);
return this;
}
public addHealthProp(health: EndpointHealth, uncertaintyInMs = 0): this {
return this.addProperty(
AlexaInterfaceType.ENDPOINT_HEALTH,
"connectivity",
{ value: health },
uncertaintyInMs
);
}
public addPowerControllerProp(
power: PowerController,
uncertaintyInMs = 0
): this {
return this.addProperty(
AlexaInterfaceType.POWER_CONTROLLER,
"powerState",
power,
uncertaintyInMs
);
}
public addTemperatureSensorProp(
scale: TemperatureSensorScale,
value: number,
uncertaintyInMs = 0
): this {
const tempValue = {
value:
scale === TemperatureSensorScale.FAHRENHEIT
? (value - 32) * (5 / 9)
: value,
scale: "CELSIUS",
};
return this.addProperty(
AlexaInterfaceType.TEMPERATURE_SENSOR,
"temperature",
tempValue,
uncertaintyInMs
);
}
public addBrightnessControllerProp(
brightness: number,
uncertaintyInMs = 0
): this {
return this.addProperty(
AlexaInterfaceType.BRIGHTNESS_CONTROLLER,
"brightness",
brightness,
uncertaintyInMs
);
}
public addColorTemperatureControllerProp(
colorTemp: number,
uncertaintyInMs = 0
): this {
return this.addProperty(
AlexaInterfaceType.COLOR_TEMPERATURE_CONTROLLER,
"colorTemperatureInKelvin",
colorTemp,
uncertaintyInMs
);
}
public addToggleControllerProp(
state: PowerController,
instance: string,
uncertaintyInMs = 0
): this {
return this.addProperty(
AlexaInterfaceType.TOGGLE_CONTROLLER,
"toggleState",
state,
uncertaintyInMs,
instance
);
}
public addContextProp(prop: ContextProperty): this {
this.context.properties.push(prop);
return this;
}
public send(): void {
const payload = {
context: this.context,
event: this.event,
};
const topic = `${this.rootTopic}/${this.endpointId}/alexaResponce`;//Yes this should be response but it is incorrect in both Alex2MQTT and Alex2ESP so for consistency is is wrong here too
const payloadStr = JSON.stringify(payload);
this.mqttClient.publish(topic, payloadStr, (err) => {
if (err) {
console.error(
"[AlexaStatusMessage] Failed to publish status message:",
err
);
} else {
// console.log(`[AlexaStatusMessage] Sent message to ${topic}`);
}
});
}
}

128
src/Device.ts Normal file
View file

@ -0,0 +1,128 @@
import { AlexaInterface, AlexaInterfaceType } from "./AlexaInterface";
import { DisplayCategory } from "./DisplayCategory";
import { EventEmitter } from "events";
import { MqttClient } from "mqtt";
import { AlexaStatusMessage } from "./AlexaStatusMessage";
class Device extends EventEmitter {
protected softwareVersion: string = "1.0.0";
private capabilities: AlexaInterface[] = [];
constructor(
private mqttClient: MqttClient,
private rootTopic: string,
public name: string,
public endpointId: string,
public displayCategory: DisplayCategory = DisplayCategory.LIGHT,
public description: string = "Alexa to Node.js bridge",
public manufacturerName: string = "Alex2Node",
public manufacturer: string = "Alex2Node",
public model: string = "Alex2Node_v1.0.0"
) {
super();
}
getName(): string {
return this.name;
}
setName(name: string): void {
this.name = name;
}
getEndpointId(): string {
return this.endpointId;
}
setDisplayCategory(category: DisplayCategory): void {
this.displayCategory = category;
}
getDisplayCategory(): DisplayCategory {
return this.displayCategory;
}
setDescription(description: string): void {
this.description = description;
}
getDescription(): string {
return this.description;
}
getStatusMessage(
correlationToken: string,
isResponse = false
): AlexaStatusMessage {
return new AlexaStatusMessage(
correlationToken,
this.rootTopic,
this.endpointId,
this.mqttClient,
isResponse
);
}
setManufacturerName(name: string): void {
this.manufacturerName = name;
}
getManufacturerName(): string {
return this.manufacturerName;
}
setManufacturer(manufacturer: string): void {
this.manufacturer = manufacturer;
}
getManufacturer(): string {
return this.manufacturer;
}
setModel(model: string): void {
this.model = model;
}
getModel(): string {
return this.model;
}
getSoftwareVersion(): string {
return this.softwareVersion;
}
addCapability(type: AlexaInterfaceType): AlexaInterface {
const existing = this.capabilities.find(
(iface) => iface.getType() === type
);
if (existing) {
return existing;
}
const newCapability = new AlexaInterface(type);
this.capabilities.push(newCapability);
// console.log(
// `Created new interface with type: ${newCapability.getTypeString()}`
// );
return newCapability;
}
getJSON(): Record<string, any> {
return {
endpointId: this.endpointId,
friendlyName: this.name,
description: this.description,
manufacturerName: this.manufacturerName,
displayCategories: [this.displayCategory],
additionalAttributes: {
manufacturer: this.manufacturer,
model: this.model,
serialNumber: "Alex2Node",
firmwareVersion: "1.0.0",
softwareVersion: this.softwareVersion,
customIdentifier: "Alex2Node",
},
capabilities: this.capabilities.map((cap) => cap.getJSON()),
};
}
}
export default Device;

58
src/DisplayCategory.ts Normal file
View file

@ -0,0 +1,58 @@
export enum DisplayCategory {
ACTIVITY_TRIGGER = "ACTIVITY_TRIGGER",
AIR_CONDITIONER = "AIR_CONDITIONER",
AIR_FRESHENER = "AIR_FRESHENER",
AIR_PURIFIER = "AIR_PURIFIER",
AIR_QUALITY_MONITOR = "AIR_QUALITY_MONITOR",
ALEXA_VOICE_ENABLED = "ALEXA_VOICE_ENABLED",
AUTO_ACCESSORY = "AUTO_ACCESSORY",
BLUETOOTH_SPEAKER = "BLUETOOTH_SPEAKER",
CAMERA = "CAMERA",
CHRISTMAS_TREE = "CHRISTMAS_TREE",
COFFEE_MAKER = "COFFEE_MAKER",
COMPUTER = "COMPUTER",
CONTACT_SENSOR = "CONTACT_SENSOR",
DISHWASHER = "DISHWASHER",
DOOR = "DOOR",
DOORBELL = "DOORBELL",
DRYER = "DRYER",
EXTERIOR_BLIND = "EXTERIOR_BLIND",
FAN = "FAN",
GAME_CONSOLE = "GAME_CONSOLE",
GARAGE_DOOR = "GARAGE_DOOR",
HEADPHONES = "HEADPHONES",
HUB = "HUB",
INTERIOR_BLIND = "INTERIOR_BLIND",
LAPTOP = "LAPTOP",
LIGHT = "LIGHT",
MICROWAVE = "MICROWAVE",
MOBILE_PHONE = "MOBILE_PHONE",
MOTION_SENSOR = "MOTION_SENSOR",
MUSIC_SYSTEM = "MUSIC_SYSTEM",
NETWORK_HARDWARE = "NETWORK_HARDWARE",
OTHER = "OTHER",
OVEN = "OVEN",
PHONE = "PHONE",
PRINTER = "PRINTER",
REMOTE = "REMOTE",
ROUTER = "ROUTER",
SCENE_TRIGGER = "SCENE_TRIGGER",
SCREEN = "SCREEN",
SECURITY_PANEL = "SECURITY_PANEL",
SECURITY_SYSTEM = "SECURITY_SYSTEM",
SLOW_COOKER = "SLOW_COOKER",
SMARTLOCK = "SMARTLOCK",
SMARTPLUG = "SMARTPLUG",
SPEAKER = "SPEAKER",
STREAMING_DEVICE = "STREAMING_DEVICE",
SWITCH = "SWITCH",
TABLET = "TABLET",
TEMPERATURE_SENSOR = "TEMPERATURE_SENSOR",
THERMOSTAT = "THERMOSTAT",
TV = "TV",
VACUUM_CLEANER = "VACUUM_CLEANER",
VEHICLE = "VEHICLE",
WASHER = "WASHER",
WATER_HEATER = "WATER_HEATER",
WEARABLE = "WEARABLE",
}

4
src/index.ts Normal file
View file

@ -0,0 +1,4 @@
export { default as Alex2MQTT } from './Alex2Node';
export { AlexaInterfaceType } from './AlexaInterface';
export { ActionMapping, AlexaActions } from './ActionMapping';
export { PowerController } from './AlexaStatusMessage';