Skip to content
Snippets Groups Projects
index.ts 1.86 KiB
Newer Older
  • Learn to ignore specific revisions
  • // import mqttAsync from "async-mqtt";
    import {
      ConnectionClient,
      Proto,
      HostConnectionOptions,
      ConnectionOptions,
    } from "../../types";
    
    import buildConnect from "../build";
    
    import rootRecordJson from "../../specs/usp-record-1-1";
    import rootMsgJson from "../../specs/usp-msg-1-1";
    
    import mqttAsync from "./async-mqtt.js";
    
    
    declare var protobuf;
    
    
    const connectClient = async (
      options: ConnectionOptions
    ): Promise<ConnectionClient> =>
      //forcing compliance for testing
      await mqttAsync.connectAsync(
        (options as HostConnectionOptions).host,
        (options as HostConnectionOptions).port,
        options.username,
    
        options.password,
        options.fromId || "proto::interop-usp-controller"
    
      );
    
    const loadProtobuf = async (): Promise<Proto> => {
      const rootRecord = protobuf.Root.fromJSON(rootRecordJson);
      const rootMsg = protobuf.Root.fromJSON(rootMsgJson);
      const header: any = rootMsg.lookupType("usp.Header");
      return { rootRecord, rootMsg, header };
    };
    
    function decodeId(array) {
      var out, i, len, c;
      var char2, char3;
    
      out = "";
      len = array.length;
      i = 0;
      while (i < len) {
        c = array[i++];
        switch (c >> 4) {
          case 0:
          case 1:
          case 2:
          case 3:
          case 4:
          case 5:
          case 6:
          case 7:
            // 0xxxxxxx
            out += String.fromCharCode(c);
            break;
          case 12:
          case 13:
            // 110x xxxx   10xx xxxx
            char2 = array[i++];
            out += String.fromCharCode(((c & 0x1f) << 6) | (char2 & 0x3f));
            break;
          case 14:
            // 1110 xxxx  10xx xxxx  10xx xxxx
            char2 = array[i++];
            char3 = array[i++];
            out += String.fromCharCode(
              ((c & 0x0f) << 12) | ((char2 & 0x3f) << 6) | ((char3 & 0x3f) << 0)
            );
            break;
        }
      }
    
      return out;
    }
    
    export default buildConnect({
      connectClient: connectClient as any,
      decodeID: decodeId,
      loadProtobuf,
    });