Skip to content
Snippets Groups Projects
mqtt.ts 1.65 KiB
Newer Older
  • Learn to ignore specific revisions
  • import mqttAsync from "async-mqtt";
    import { decodeId } from "../commands";
    import {
      ConnectionOptions,
      ConnectionClient,
      URLConnectionOptions,
      Proto,
    
      ConnectClientFn,
    
      USPVersion,
    
    } from "../types";
    
    import buildConnect from "./build";
    import protobuf from "protobufjs";
    
    import { jsonRoots } from "./util";
    
    export const isURL = (opts: ConnectionOptions): opts is URLConnectionOptions =>
    
    const correctOptions = (opts: ConnectionOptions): ConnectionOptions => ({
      ...opts,
      clientId: opts.clientId || opts.fromId,
      clean: opts.cleanSession ?? false,
    });
    
    export const connectClient: ConnectClientFn = async (initialOpts) => {
      const opts = correctOptions(initialOpts);
      return isURL(opts)
    
        ? (mqttAsync.connectAsync(
            opts.url,
            opts as any
          ) as unknown as ConnectionClient)
        : opts.protocol?.startsWith("ws")
    
        ? (mqttAsync.connectAsync(`${opts.protocol}://${opts.host}:${opts.port}`, {
            ...opts,
            hostname: opts?.hostname || opts.host,
    
            ...(opts.path && !opts.path.startsWith("/")
              ? { path: `/${opts.path}` }
              : {}),
    
          } as any) as unknown as ConnectionClient)
    
        : (mqttAsync.connectAsync(opts) as unknown as ConnectionClient);
    
    export const loadProtobuf = async (version: USPVersion): Promise<Proto> => {
    
      const [rootRecordJson, rootMsgJson] = jsonRoots[version];
    
      const rootRecord = protobuf.Root.fromJSON(rootRecordJson);
      const rootMsg = protobuf.Root.fromJSON(rootMsgJson);
      const header: any = rootMsg.lookupType("usp.Header");
      return { rootRecord, rootMsg, header };
    };
    
    export default buildConnect({
      connectClient,
      decodeID: decodeId,
      loadProtobuf,
    });