You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
273 lines
8.8 KiB
273 lines
8.8 KiB
7 years ago
|
import { action, observable, when } from "mobx";
|
||
7 years ago
|
import { update } from "serializr";
|
||
|
|
||
7 years ago
|
import * as rpc from "@common/jsonRpc";
|
||
7 years ago
|
import logger from "@common/logger";
|
||
7 years ago
|
import * as deviceRequests from "@common/sprinklersRpc/deviceRequests";
|
||
|
import { ErrorCode } from "@common/sprinklersRpc/ErrorCode";
|
||
|
import * as s from "@common/sprinklersRpc/index";
|
||
|
import * as schema from "@common/sprinklersRpc/schema/index";
|
||
|
import { seralizeRequest } from "@common/sprinklersRpc/schema/requests";
|
||
|
import * as ws from "@common/sprinklersRpc/websocketData";
|
||
7 years ago
|
|
||
|
const log = logger.child({ source: "websocket" });
|
||
|
|
||
7 years ago
|
const TIMEOUT_MS = 5000;
|
||
7 years ago
|
const RECONNECT_TIMEOUT_MS = 5000;
|
||
7 years ago
|
|
||
7 years ago
|
// tslint:disable:member-ordering
|
||
|
|
||
7 years ago
|
export class WSSprinklersDevice extends s.SprinklersDevice {
|
||
|
readonly api: WebSocketApiClient;
|
||
7 years ago
|
|
||
7 years ago
|
private _id: string;
|
||
|
|
||
|
constructor(api: WebSocketApiClient, id: string) {
|
||
7 years ago
|
super();
|
||
|
this.api = api;
|
||
7 years ago
|
this._id = id;
|
||
7 years ago
|
when(() => api.connectionState.isConnected || false, () => {
|
||
7 years ago
|
this.subscribe();
|
||
7 years ago
|
});
|
||
7 years ago
|
}
|
||
|
|
||
|
get id() {
|
||
7 years ago
|
return this._id;
|
||
|
}
|
||
|
|
||
7 years ago
|
async subscribe() {
|
||
7 years ago
|
if (this.api.accessToken) {
|
||
|
await this.api.authenticate(this.api.accessToken);
|
||
|
}
|
||
7 years ago
|
const subscribeRequest: ws.IDeviceSubscribeRequest = {
|
||
|
deviceId: this.id,
|
||
|
};
|
||
7 years ago
|
try {
|
||
|
await this.api.makeRequest("deviceSubscribe", subscribeRequest);
|
||
|
this.connectionState.serverToBroker = true;
|
||
|
this.connectionState.clientToServer = true;
|
||
|
} catch (err) {
|
||
7 years ago
|
if ((err as ws.IError).code === ErrorCode.NoPermission) {
|
||
7 years ago
|
this.connectionState.hasPermission = false;
|
||
|
} else {
|
||
|
log.error({ err });
|
||
|
}
|
||
7 years ago
|
}
|
||
|
}
|
||
|
|
||
7 years ago
|
makeRequest(request: deviceRequests.Request): Promise<deviceRequests.Response> {
|
||
7 years ago
|
return this.api.makeDeviceCall(this.id, request);
|
||
7 years ago
|
}
|
||
|
}
|
||
|
|
||
7 years ago
|
export class WebSocketApiClient implements s.SprinklersRPC {
|
||
7 years ago
|
readonly webSocketUrl: string;
|
||
7 years ago
|
|
||
|
devices: Map<string, WSSprinklersDevice> = new Map();
|
||
7 years ago
|
@observable connectionState: s.ConnectionState = new s.ConnectionState();
|
||
7 years ago
|
socket: WebSocket | null = null;
|
||
7 years ago
|
|
||
|
private nextRequestId = Math.round(Math.random() * 1000000);
|
||
|
private responseCallbacks: ws.ServerResponseHandlers = {};
|
||
7 years ago
|
private reconnectTimer: number | null = null;
|
||
7 years ago
|
accessToken: string | undefined;
|
||
7 years ago
|
|
||
7 years ago
|
get connected(): boolean {
|
||
7 years ago
|
return this.connectionState.isConnected || false;
|
||
7 years ago
|
}
|
||
|
|
||
7 years ago
|
constructor(webSocketUrl: string) {
|
||
|
this.webSocketUrl = webSocketUrl;
|
||
7 years ago
|
this.connectionState.clientToServer = false;
|
||
|
this.connectionState.serverToBroker = false;
|
||
7 years ago
|
}
|
||
|
|
||
|
start() {
|
||
|
log.debug({ url: this.webSocketUrl }, "connecting to websocket");
|
||
7 years ago
|
this._connect();
|
||
|
}
|
||
|
|
||
|
stop() {
|
||
|
if (this.reconnectTimer != null) {
|
||
|
clearTimeout(this.reconnectTimer);
|
||
|
this.reconnectTimer = null;
|
||
|
}
|
||
|
if (this.socket != null) {
|
||
|
this.socket.close();
|
||
|
this.socket = null;
|
||
|
}
|
||
7 years ago
|
}
|
||
|
|
||
7 years ago
|
getDevice(id: string): s.SprinklersDevice {
|
||
|
let device = this.devices.get(id);
|
||
|
if (!device) {
|
||
|
device = new WSSprinklersDevice(this, id);
|
||
|
this.devices.set(id, device);
|
||
7 years ago
|
}
|
||
7 years ago
|
return device;
|
||
7 years ago
|
}
|
||
|
|
||
7 years ago
|
removeDevice(id: string) {
|
||
7 years ago
|
// NOT IMPLEMENTED
|
||
|
}
|
||
|
|
||
7 years ago
|
async authenticate(accessToken: string): Promise<ws.IAuthenticateResponse> {
|
||
|
return this.makeRequest("authenticate", { accessToken });
|
||
|
}
|
||
|
|
||
7 years ago
|
// args must all be JSON serializable
|
||
7 years ago
|
async makeDeviceCall(deviceId: string, request: deviceRequests.Request): Promise<deviceRequests.Response> {
|
||
7 years ago
|
if (this.socket == null) {
|
||
7 years ago
|
const error: ws.IError = {
|
||
7 years ago
|
code: ErrorCode.ServerDisconnected,
|
||
|
message: "the server is not connected",
|
||
|
};
|
||
7 years ago
|
throw error;
|
||
7 years ago
|
}
|
||
7 years ago
|
const requestData = seralizeRequest(request);
|
||
7 years ago
|
const data: ws.IDeviceCallRequest = { deviceId, data: requestData };
|
||
|
const resData = await this.makeRequest("deviceCall", data);
|
||
|
if (resData.data.result === "error") {
|
||
|
throw {
|
||
|
code: resData.data.code,
|
||
|
message: resData.data.message,
|
||
|
data: resData.data,
|
||
|
};
|
||
|
} else {
|
||
|
return resData.data;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
makeRequest<Method extends ws.ClientRequestMethods>(method: Method, params: ws.IClientRequestTypes[Method]):
|
||
|
Promise<ws.IServerResponseTypes[Method]> {
|
||
|
const id = this.nextRequestId++;
|
||
|
return new Promise<ws.IServerResponseTypes[Method]>((resolve, reject) => {
|
||
7 years ago
|
let timeoutHandle: number;
|
||
7 years ago
|
this.responseCallbacks[id] = (response) => {
|
||
7 years ago
|
clearTimeout(timeoutHandle);
|
||
7 years ago
|
delete this.responseCallbacks[id];
|
||
|
if (response.result === "success") {
|
||
|
resolve(response.data);
|
||
7 years ago
|
} else {
|
||
7 years ago
|
reject(response.error);
|
||
7 years ago
|
}
|
||
|
};
|
||
7 years ago
|
timeoutHandle = window.setTimeout(() => {
|
||
7 years ago
|
delete this.responseCallbacks[id];
|
||
|
const res: ws.ErrorData = {
|
||
|
result: "error", error: {
|
||
|
code: ErrorCode.Timeout,
|
||
|
message: "the request timed out",
|
||
|
},
|
||
7 years ago
|
};
|
||
|
reject(res);
|
||
|
}, TIMEOUT_MS);
|
||
7 years ago
|
this.sendRequest(id, method, params);
|
||
7 years ago
|
});
|
||
7 years ago
|
}
|
||
|
|
||
|
private sendMessage(data: ws.ClientMessage) {
|
||
|
if (!this.socket) {
|
||
|
throw new Error("WebSocketApiClient is not connected");
|
||
|
}
|
||
7 years ago
|
this.socket.send(JSON.stringify(data));
|
||
7 years ago
|
}
|
||
|
|
||
|
private sendRequest<Method extends ws.ClientRequestMethods>(
|
||
|
id: number, method: Method, params: ws.IClientRequestTypes[Method],
|
||
|
) {
|
||
|
this.sendMessage({ type: "request", id, method, params });
|
||
7 years ago
|
}
|
||
|
|
||
7 years ago
|
private _reconnect = () => {
|
||
|
this._connect();
|
||
|
}
|
||
|
|
||
|
private _connect() {
|
||
|
this.socket = new WebSocket(this.webSocketUrl);
|
||
|
this.socket.onopen = this.onOpen.bind(this);
|
||
|
this.socket.onclose = this.onClose.bind(this);
|
||
|
this.socket.onerror = this.onError.bind(this);
|
||
|
this.socket.onmessage = this.onMessage.bind(this);
|
||
|
}
|
||
|
|
||
7 years ago
|
private onOpen() {
|
||
|
log.info("established websocket connection");
|
||
7 years ago
|
this.connectionState.clientToServer = true;
|
||
7 years ago
|
}
|
||
|
|
||
7 years ago
|
/* tslint:disable-next-line:member-ordering */
|
||
|
private onDisconnect = action(() => {
|
||
|
this.connectionState.serverToBroker = null;
|
||
|
this.connectionState.clientToServer = false;
|
||
|
});
|
||
|
|
||
7 years ago
|
private onClose(event: CloseEvent) {
|
||
|
log.info({ reason: event.reason, wasClean: event.wasClean },
|
||
|
"disconnected from websocket");
|
||
7 years ago
|
this.onDisconnect();
|
||
7 years ago
|
this.reconnectTimer = window.setTimeout(this._reconnect, RECONNECT_TIMEOUT_MS);
|
||
7 years ago
|
}
|
||
|
|
||
|
private onError(event: Event) {
|
||
7 years ago
|
log.error({ event }, "websocket error");
|
||
|
action(() => {
|
||
|
this.connectionState.serverToBroker = null;
|
||
|
this.connectionState.clientToServer = false;
|
||
|
});
|
||
|
this.onDisconnect();
|
||
7 years ago
|
}
|
||
|
|
||
|
private onMessage(event: MessageEvent) {
|
||
7 years ago
|
let data: ws.ServerMessage;
|
||
7 years ago
|
try {
|
||
|
data = JSON.parse(event.data);
|
||
|
} catch (err) {
|
||
|
return log.error({ event, err }, "received invalid websocket message");
|
||
|
}
|
||
7 years ago
|
log.trace({ data }, "websocket message");
|
||
7 years ago
|
switch (data.type) {
|
||
7 years ago
|
case "notification":
|
||
|
this.onNotification(data);
|
||
7 years ago
|
break;
|
||
7 years ago
|
case "response":
|
||
|
this.onResponse(data);
|
||
7 years ago
|
break;
|
||
7 years ago
|
default:
|
||
|
log.warn({ data }, "unsupported event type received");
|
||
|
}
|
||
|
}
|
||
|
|
||
7 years ago
|
private onNotification(data: ws.ServerNotification) {
|
||
|
try {
|
||
|
rpc.handleNotification(this.notificationHandlers, data);
|
||
|
} catch (err) {
|
||
|
logger.error({ err }, "error handling server notification");
|
||
7 years ago
|
}
|
||
|
}
|
||
|
|
||
7 years ago
|
private onResponse(data: ws.ServerResponse) {
|
||
|
try {
|
||
|
rpc.handleResponse(this.responseCallbacks, data);
|
||
|
} catch (err) {
|
||
|
log.error({ err }, "error handling server response");
|
||
7 years ago
|
}
|
||
|
}
|
||
7 years ago
|
|
||
7 years ago
|
private notificationHandlers: ws.ServerNotificationHandlers = {
|
||
|
brokerConnectionUpdate: (data: ws.IBrokerConnectionUpdate) => {
|
||
|
this.connectionState.serverToBroker = data.brokerConnected;
|
||
|
},
|
||
|
deviceUpdate: (data: ws.IDeviceUpdate) => {
|
||
|
const device = this.devices.get(data.deviceId);
|
||
|
if (!device) {
|
||
|
return log.warn({ data }, "invalid deviceUpdate received");
|
||
|
}
|
||
|
update(schema.sprinklersDevice, device, data.data);
|
||
|
},
|
||
7 years ago
|
error: (data: ws.IError) => {
|
||
7 years ago
|
log.warn({ err: data }, "server error");
|
||
|
},
|
||
|
};
|
||
7 years ago
|
}
|