Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 'use strict';
- export default class Engine{
- constructor(url, response_handler) {
- this.socket = new WebSocket(url);
- this.socketQueueId = 0;
- this.socketQueue = {};
- this.response_handler = response_handler;
- this.socket.onmessage = (event) => {
- let response = {};
- try {
- response = JSON.parse(event.data);
- } catch(e) {
- // string received
- console.log('Engine:', event.data);
- }
- // RPC responses
- if (typeof(response['cmd_id']) != 'undefined' && typeof(this.socketQueue['i_'+response['cmd_id']]) == 'function') {
- // action response
- let execFunc = this.socketQueue['i_'+response['cmd_id']];
- execFunc(response);
- delete this.socketQueue['i_'+response['cmd_id']];
- }
- else {
- // non RPC responses
- if (response != 'undefined' && Object.keys(response).length != 0) {
- switch (response.entity == '--SERVICE--') {
- case true:
- // engine internal responses
- if (response.action == 'init') {
- console.log('Engine v', response.data.version);
- }
- break;
- case false:
- switch (response.action != null && response.entity != null) {
- case true:
- this.response_handler(response);
- break;
- case false:
- // errors and other
- console.log('Engine:', response.msg, response.data);
- }
- break;
- }
- }
- else {
- console.log(response);
- }
- }
- };
- this.socket.onopen = (event) => {
- console.log('Socket open.');
- };
- this.socket.onclose = () => {
- console.log('Socket close.');
- }
- }
- send(message, callback) {
- this.waitForConnection(() => {
- if (typeof callback !== 'undefined') {
- this.socketQueueId++;
- this.socketQueue['i_'+this.socketQueueId] = callback;
- message.cmd_id = this.socketQueueId;
- this.socket.send(JSON.stringify(message));
- }
- }, 1000);
- };
- waitForConnection(send_func, interval) {
- if (this.socket.readyState === 1) {
- send_func();
- } else {
- let that = this;
- setTimeout(function () {
- that.waitForConnection(send_func, interval);
- }, interval);
- }
- };
- action(message) {
- let inst = this;
- return new Promise((resolve, reject) => {
- inst.send(message, (response) => {resolve(response)});
- });
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement