Newer
Older
import mqttAsync from "async-mqtt";
import { decodeId } from "../commands";
import {
ConnectionOptions,
ConnectionClient,
URLConnectionOptions,
Proto,
} from "../types";
import buildConnect from "./build";
import protobuf from "protobufjs";
Marin Karamihalev
committed
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);
};
Marin Karamihalev
committed
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,
});