home-assistant-js-websocket
Version:
Home Assistant websocket client
54 lines (53 loc) • 2.41 kB
TypeScript
import { ConnectionOptions, MessageBase } from "./types";
export declare type ConnectionEventListener = (conn: Connection, eventData?: any) => void;
declare type Events = "ready" | "disconnected" | "reconnect-error";
declare type SubscriptionUnsubscribe = () => Promise<void>;
interface SubscribeEventCommmandInFlight<T> {
resolve: (result?: any) => void;
reject: (err: any) => void;
callback: (ev: T) => void;
subscribe: () => Promise<SubscriptionUnsubscribe>;
unsubscribe: SubscriptionUnsubscribe;
}
declare type CommandWithAnswerInFlight = {
resolve: (result?: any) => void;
reject: (err: any) => void;
};
declare type CommandInFlight = SubscribeEventCommmandInFlight<any> | CommandWithAnswerInFlight;
export declare class Connection {
options: ConnectionOptions;
commandId: number;
commands: Map<number, CommandInFlight>;
eventListeners: Map<string, ConnectionEventListener[]>;
closeRequested: boolean;
socket: WebSocket;
constructor(socket: WebSocket, options: ConnectionOptions);
setSocket(socket: WebSocket): void;
addEventListener(eventType: Events, callback: ConnectionEventListener): void;
removeEventListener(eventType: Events, callback: ConnectionEventListener): void;
fireEvent(eventType: Events, eventData?: any): void;
close(): void;
/**
* Subscribe to a specific or all events.
*
* @param callback Callback to be called when a new event fires
* @param eventType
* @returns promise that resolves to an unsubscribe function
*/
subscribeEvents<EventType>(callback: (ev: EventType) => void, eventType?: string): Promise<SubscriptionUnsubscribe>;
ping(): Promise<unknown>;
sendMessage(message: MessageBase, commandId?: number): void;
sendMessagePromise<Result>(message: MessageBase): Promise<Result>;
/**
* Call a websocket command that starts a subscription on the backend.
*
* @param message the message to start the subscription
* @param callback the callback to be called when a new item arrives
* @returns promise that resolves to an unsubscribe function
*/
subscribeMessage<Result>(callback: (result: Result) => void, subscribeMessage: MessageBase): Promise<SubscriptionUnsubscribe>;
private _handleMessage;
private _handleClose;
private _genCmdId;
}
export {};