Files

82 lines
2.8 KiB
TypeScript
Raw Permalink Normal View History

2026-05-05 12:03:46 +00:00
import * as plugins from './plugins.js';
export interface IShxApiClientOptions {
hubUrl?: string;
useSocket?: boolean;
}
export class SmarthomeExchangeApiClient {
private hubUrl: string;
public typedrouter = new plugins.typedrequest.TypedRouter();
public typedsocketClient?: plugins.typedsocket.TypedSocket;
constructor(optionsArg: IShxApiClientOptions = {}) {
this.hubUrl = (optionsArg.hubUrl || 'http://localhost:8080').replace(/\/$/, '');
}
private get httpEndpoint() {
return `${this.hubUrl}/typedrequest`;
}
private createWsRequest<T extends plugins.typedRequestInterfaces.ITypedRequest>(operationArg: string) {
return this.typedsocketClient?.createTypedRequest<T>(operationArg);
}
private createHttpRequest<T extends plugins.typedRequestInterfaces.ITypedRequest>(operationArg: string) {
return new plugins.typedrequest.TypedRequest<T>(this.httpEndpoint, operationArg);
}
private async fire<T extends plugins.typedRequestInterfaces.ITypedRequest>(
operationArg: string,
payloadArg: T['request']
): Promise<T['response']> {
const wsRequest = this.createWsRequest<T>(operationArg);
if (wsRequest) {
return wsRequest.fire(payloadArg);
}
return this.createHttpRequest<T>(operationArg).fire(payloadArg);
}
public async start() {
this.typedsocketClient = await plugins.typedsocket.TypedSocket.createClient(
this.typedrouter,
this.hubUrl
);
}
public async stop() {
await this.typedsocketClient?.stop();
this.typedsocketClient = undefined;
}
public async listDevices(requestArg: plugins.shxInterfaces.request.IReq_ListDevices['request'] = {}) {
return this.fire<plugins.shxInterfaces.request.IReq_ListDevices>('listDevices', requestArg);
}
public async listAgents() {
return this.fire<plugins.shxInterfaces.request.IReq_ListAgents>('listAgents', {});
}
public async listTools(requestArg: plugins.shxInterfaces.request.IReq_ListTools['request'] = {}) {
return this.fire<plugins.shxInterfaces.request.IReq_ListTools>('listTools', requestArg);
}
public async getHomeSnapshot() {
return this.fire<plugins.shxInterfaces.request.IReq_GetHomeSnapshot>('getHomeSnapshot', {});
}
public async executeToolPlan(planArg: plugins.shxInterfaces.data.IToolPlan) {
return this.fire<plugins.shxInterfaces.request.IReq_ExecuteToolPlan>('executeToolPlan', {
plan: planArg,
});
}
public async listApprovals(requestArg: plugins.shxInterfaces.request.IReq_ListApprovals['request'] = {}) {
return this.fire<plugins.shxInterfaces.request.IReq_ListApprovals>('listApprovals', requestArg);
}
public async submitApproval(requestArg: plugins.shxInterfaces.request.IReq_SubmitApproval['request']) {
return this.fire<plugins.shxInterfaces.request.IReq_SubmitApproval>('submitApproval', requestArg);
}
}