Migrate from BUN_ENV to NODE_ENV and update Home Assistant implementation
This commit is contained in:
@@ -1,11 +1,10 @@
|
||||
import { CreateApplication, TServiceParams, ServiceFunction, AlsExtension, GetApisResult, ILogger, InternalDefinition, TContext, TInjectedConfig, TLifecycleBase, TScheduler } from "@digital-alchemy/core";
|
||||
import { Area, Backup, CallProxy, Configure, Device, EntityManager, EventsService, FetchAPI, FetchInternals, Floor, IDByExtension, Label, LIB_HASS, ReferenceService, Registry, WebsocketAPI, Zone } from "@digital-alchemy/hass";
|
||||
import { DomainSchema } from "../schemas.js";
|
||||
import { HASS_CONFIG } from "../config/index.js";
|
||||
import WebSocket from 'ws';
|
||||
import { HASS_CONFIG } from "../config/hass.config.js";
|
||||
import { WebSocket } from 'ws';
|
||||
import { EventEmitter } from 'events';
|
||||
import * as HomeAssistant from '../types/hass.js';
|
||||
import { HassEntity, HassEvent, HassService } from '../interfaces/hass.js';
|
||||
|
||||
type Environments = "development" | "production" | "test";
|
||||
|
||||
@@ -19,23 +18,38 @@ type HassServices = {
|
||||
};
|
||||
|
||||
// Define the type for Home Assistant instance
|
||||
interface HassInstance {
|
||||
states: {
|
||||
get: () => Promise<HassEntity[]>;
|
||||
subscribe: (callback: (states: HassEntity[]) => void) => Promise<number>;
|
||||
unsubscribe: (subscription: number) => void;
|
||||
};
|
||||
services: {
|
||||
get: () => Promise<Record<string, Record<string, HassService>>>;
|
||||
call: (domain: string, service: string, serviceData?: Record<string, any>) => Promise<void>;
|
||||
};
|
||||
connection: {
|
||||
socket: WebSocket;
|
||||
subscribeEvents: (callback: (event: HassEvent) => void, eventType?: string) => Promise<number>;
|
||||
unsubscribeEvents: (subscription: number) => void;
|
||||
};
|
||||
subscribeEvents: (callback: (event: HassEvent) => void, eventType?: string) => Promise<number>;
|
||||
unsubscribeEvents: (subscription: number) => void;
|
||||
interface HassInstance extends TServiceParams {
|
||||
baseUrl: string;
|
||||
token: string;
|
||||
wsClient: HassWebSocketClient | undefined;
|
||||
services: HassServices;
|
||||
als: AlsExtension;
|
||||
context: TContext;
|
||||
event: EventEmitter<[never]>;
|
||||
internal: InternalDefinition;
|
||||
lifecycle: TLifecycleBase;
|
||||
logger: ILogger;
|
||||
scheduler: TScheduler;
|
||||
config: TInjectedConfig;
|
||||
params: TServiceParams;
|
||||
hass: GetApisResult<{
|
||||
area: typeof Area;
|
||||
backup: typeof Backup;
|
||||
call: typeof CallProxy;
|
||||
configure: typeof Configure;
|
||||
device: typeof Device;
|
||||
entity: typeof EntityManager;
|
||||
events: typeof EventsService;
|
||||
fetch: typeof FetchAPI;
|
||||
floor: typeof Floor;
|
||||
idBy: typeof IDByExtension;
|
||||
internals: typeof FetchInternals;
|
||||
label: typeof Label;
|
||||
refBy: typeof ReferenceService;
|
||||
registry: typeof Registry;
|
||||
socket: typeof WebsocketAPI;
|
||||
zone: typeof Zone;
|
||||
}>;
|
||||
}
|
||||
|
||||
// Configuration type for application with more specific constraints
|
||||
@@ -286,79 +300,7 @@ export class HassInstanceImpl implements HassInstance {
|
||||
public readonly token: string;
|
||||
public wsClient: HassWebSocketClient | undefined;
|
||||
|
||||
public readonly services: HassInstance['services'];
|
||||
public readonly states: HassInstance['states'];
|
||||
public readonly connection: HassInstance['connection'];
|
||||
|
||||
constructor(baseUrl: string, token: string) {
|
||||
this.baseUrl = baseUrl;
|
||||
this.token = token;
|
||||
|
||||
// Initialize services
|
||||
this.services = {
|
||||
get: async () => {
|
||||
const response = await fetch(`${this.baseUrl}/api/services`, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.token}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to fetch services: ${response.statusText}`);
|
||||
}
|
||||
return response.json();
|
||||
},
|
||||
call: async (domain: string, service: string, serviceData?: Record<string, any>) => {
|
||||
const response = await fetch(`${this.baseUrl}/api/services/${domain}/${service}`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.token}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(serviceData),
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(`Service call failed: ${response.statusText}`);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Initialize states
|
||||
this.states = {
|
||||
get: async () => {
|
||||
const response = await fetch(`${this.baseUrl}/api/states`, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.token}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to fetch states: ${response.statusText}`);
|
||||
}
|
||||
return response.json();
|
||||
},
|
||||
subscribe: async (callback: (states: HassEntity[]) => void) => {
|
||||
return this.subscribeEvents((event: HassEvent) => {
|
||||
if (event.event_type === 'state_changed') {
|
||||
this.states.get().then(callback);
|
||||
}
|
||||
}, 'state_changed');
|
||||
},
|
||||
unsubscribe: (subscription: number) => {
|
||||
this.unsubscribeEvents(subscription);
|
||||
}
|
||||
};
|
||||
|
||||
// Initialize connection
|
||||
this.connection = {
|
||||
socket: new WebSocket(this.baseUrl.replace(/^http/, 'ws') + '/api/websocket'),
|
||||
subscribeEvents: this.subscribeEvents.bind(this),
|
||||
unsubscribeEvents: this.unsubscribeEvents.bind(this)
|
||||
};
|
||||
|
||||
this.initialize();
|
||||
}
|
||||
|
||||
public services!: HassServices;
|
||||
public als!: AlsExtension;
|
||||
public context!: TContext;
|
||||
public event!: EventEmitter<[never]>;
|
||||
@@ -387,8 +329,15 @@ export class HassInstanceImpl implements HassInstance {
|
||||
zone: typeof Zone;
|
||||
}>;
|
||||
|
||||
constructor(baseUrl: string, token: string) {
|
||||
this.baseUrl = baseUrl;
|
||||
this.token = token;
|
||||
this.initialize();
|
||||
}
|
||||
|
||||
private initialize() {
|
||||
// Initialize all required properties with proper type instantiation
|
||||
this.services = {} as HassServices;
|
||||
this.als = {} as AlsExtension;
|
||||
this.context = {} as TContext;
|
||||
this.event = new EventEmitter();
|
||||
@@ -448,7 +397,7 @@ export class HassInstanceImpl implements HassInstance {
|
||||
}
|
||||
}
|
||||
|
||||
async subscribeEvents(callback: (event: HassEvent) => void, eventType?: string): Promise<number> {
|
||||
async subscribeEvents(callback: (event: HomeAssistant.Event) => void, eventType?: string): Promise<number> {
|
||||
if (!this.wsClient) {
|
||||
this.wsClient = new HassWebSocketClient(
|
||||
this.baseUrl.replace(/^http/, 'ws') + '/api/websocket',
|
||||
@@ -457,20 +406,7 @@ export class HassInstanceImpl implements HassInstance {
|
||||
await this.wsClient.connect();
|
||||
}
|
||||
|
||||
return this.wsClient.subscribeEvents((data: any) => {
|
||||
const hassEvent: HassEvent = {
|
||||
event_type: data.event_type,
|
||||
data: data.data,
|
||||
origin: data.origin,
|
||||
time_fired: data.time_fired,
|
||||
context: {
|
||||
id: data.context.id,
|
||||
parent_id: data.context.parent_id,
|
||||
user_id: data.context.user_id
|
||||
}
|
||||
};
|
||||
callback(hassEvent);
|
||||
}, eventType);
|
||||
return this.wsClient.subscribeEvents(callback, eventType);
|
||||
}
|
||||
|
||||
async unsubscribeEvents(subscriptionId: number): Promise<void> {
|
||||
@@ -480,208 +416,14 @@ export class HassInstanceImpl implements HassInstance {
|
||||
}
|
||||
}
|
||||
|
||||
class HomeAssistantInstance implements HassInstance {
|
||||
private messageId = 1;
|
||||
private messageCallbacks = new Map<number, (result: any) => void>();
|
||||
private eventCallbacks = new Map<number, (event: HassEvent) => void>();
|
||||
private stateCallbacks = new Map<number, (states: HassEntity[]) => void>();
|
||||
private _authenticated = false;
|
||||
private socket: WebSocket;
|
||||
private readonly _states: HassInstance['states'];
|
||||
private readonly _services: HassInstance['services'];
|
||||
private readonly _connection: HassInstance['connection'];
|
||||
|
||||
constructor() {
|
||||
if (!HASS_CONFIG.TOKEN) {
|
||||
throw new Error('Home Assistant token is required');
|
||||
}
|
||||
|
||||
this.socket = new WebSocket(HASS_CONFIG.SOCKET_URL);
|
||||
|
||||
this._states = {
|
||||
get: async (): Promise<HassEntity[]> => {
|
||||
const message = {
|
||||
type: 'get_states'
|
||||
};
|
||||
return this.sendMessage(message);
|
||||
},
|
||||
|
||||
subscribe: async (callback: (states: HassEntity[]) => void): Promise<number> => {
|
||||
const id = this.messageId++;
|
||||
this.stateCallbacks.set(id, callback);
|
||||
|
||||
const message = {
|
||||
type: 'subscribe_events',
|
||||
event_type: 'state_changed'
|
||||
};
|
||||
|
||||
await this.sendMessage(message);
|
||||
return id;
|
||||
},
|
||||
|
||||
unsubscribe: (subscription: number): void => {
|
||||
this.stateCallbacks.delete(subscription);
|
||||
}
|
||||
};
|
||||
|
||||
this._services = {
|
||||
get: async (): Promise<Record<string, Record<string, HassService>>> => {
|
||||
const message = {
|
||||
type: 'get_services'
|
||||
};
|
||||
return this.sendMessage(message);
|
||||
},
|
||||
|
||||
call: async (domain: string, service: string, serviceData?: Record<string, any>): Promise<void> => {
|
||||
const message = {
|
||||
type: 'call_service',
|
||||
domain,
|
||||
service,
|
||||
service_data: serviceData
|
||||
};
|
||||
await this.sendMessage(message);
|
||||
}
|
||||
};
|
||||
|
||||
this._connection = {
|
||||
socket: this.socket,
|
||||
subscribeEvents: this.subscribeEvents.bind(this),
|
||||
unsubscribeEvents: this.unsubscribeEvents.bind(this)
|
||||
};
|
||||
|
||||
this.setupWebSocket();
|
||||
}
|
||||
|
||||
get authenticated(): boolean {
|
||||
return this._authenticated;
|
||||
}
|
||||
|
||||
get states(): HassInstance['states'] {
|
||||
return this._states;
|
||||
}
|
||||
|
||||
get services(): HassInstance['services'] {
|
||||
return this._services;
|
||||
}
|
||||
|
||||
get connection(): HassInstance['connection'] {
|
||||
return this._connection;
|
||||
}
|
||||
|
||||
private setupWebSocket() {
|
||||
this.socket.on('open', () => {
|
||||
this.authenticate();
|
||||
});
|
||||
|
||||
this.socket.on('message', (data: WebSocket.Data) => {
|
||||
if (typeof data === 'string') {
|
||||
const message = JSON.parse(data);
|
||||
this.handleMessage(message);
|
||||
}
|
||||
});
|
||||
|
||||
this.socket.on('close', () => {
|
||||
console.log('WebSocket connection closed');
|
||||
// Implement reconnection logic here
|
||||
});
|
||||
|
||||
this.socket.on('error', (error) => {
|
||||
console.error('WebSocket error:', error);
|
||||
});
|
||||
}
|
||||
|
||||
private authenticate() {
|
||||
const auth = {
|
||||
type: 'auth',
|
||||
access_token: HASS_CONFIG.TOKEN
|
||||
};
|
||||
this.socket.send(JSON.stringify(auth));
|
||||
}
|
||||
|
||||
private handleMessage(message: any) {
|
||||
if (message.type === 'auth_ok') {
|
||||
this._authenticated = true;
|
||||
console.log('Authenticated with Home Assistant');
|
||||
return;
|
||||
}
|
||||
|
||||
if (message.type === 'auth_invalid') {
|
||||
console.error('Authentication failed:', message.message);
|
||||
return;
|
||||
}
|
||||
|
||||
if (message.type === 'event') {
|
||||
const callback = this.eventCallbacks.get(message.id);
|
||||
if (callback) {
|
||||
callback(message.event);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (message.type === 'result') {
|
||||
const callback = this.messageCallbacks.get(message.id);
|
||||
if (callback) {
|
||||
callback(message.result);
|
||||
this.messageCallbacks.delete(message.id);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
private async sendMessage(message: any): Promise<any> {
|
||||
if (!this._authenticated) {
|
||||
throw new Error('Not authenticated with Home Assistant');
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const id = this.messageId++;
|
||||
message.id = id;
|
||||
|
||||
this.messageCallbacks.set(id, resolve);
|
||||
this.socket.send(JSON.stringify(message));
|
||||
|
||||
// Add timeout
|
||||
setTimeout(() => {
|
||||
this.messageCallbacks.delete(id);
|
||||
reject(new Error('Message timeout'));
|
||||
}, 10000);
|
||||
});
|
||||
}
|
||||
|
||||
public async subscribeEvents(callback: (event: HassEvent) => void, eventType?: string): Promise<number> {
|
||||
const id = this.messageId++;
|
||||
this.eventCallbacks.set(id, callback);
|
||||
|
||||
const message = {
|
||||
type: 'subscribe_events',
|
||||
event_type: eventType
|
||||
};
|
||||
|
||||
await this.sendMessage(message);
|
||||
return id;
|
||||
}
|
||||
|
||||
public unsubscribeEvents(subscription: number): void {
|
||||
this.eventCallbacks.delete(subscription);
|
||||
}
|
||||
}
|
||||
|
||||
let hassInstance: HomeAssistantInstance | null = null;
|
||||
let hassInstance: HassInstance | null = null;
|
||||
|
||||
export async function get_hass(): Promise<HassInstance> {
|
||||
if (!hassInstance) {
|
||||
hassInstance = new HomeAssistantInstance();
|
||||
// Wait for authentication
|
||||
await new Promise<void>((resolve) => {
|
||||
const checkAuth = () => {
|
||||
if (hassInstance?.authenticated) {
|
||||
resolve();
|
||||
} else {
|
||||
setTimeout(checkAuth, 100);
|
||||
}
|
||||
};
|
||||
checkAuth();
|
||||
});
|
||||
// Safely get configuration keys, providing an empty object as fallback
|
||||
const _sortedConfigKeys = Object.keys(MY_APP.configuration ?? {}).sort();
|
||||
const instance = await MY_APP.bootstrap();
|
||||
hassInstance = instance as HassInstance;
|
||||
}
|
||||
return hassInstance;
|
||||
}
|
||||
1311
src/index.ts
1311
src/index.ts
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user