UNPKG

@foxglove/ws-protocol-examples

Version:

Foxglove WebSocket protocol examples

53 lines 2.43 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const tslib_1 = require("tslib"); const ws_protocol_1 = require("@foxglove/ws-protocol"); const commander_1 = require("commander"); const debug_1 = tslib_1.__importDefault(require("debug")); const protobufjs_1 = tslib_1.__importDefault(require("protobufjs")); const descriptor_1 = require("protobufjs/ext/descriptor"); const ws_1 = tslib_1.__importDefault(require("ws")); const log = (0, debug_1.default)("foxglove:simple-client"); debug_1.default.enable("foxglove:*"); async function main(url) { const address = url.startsWith("ws://") || url.startsWith("wss://") ? url : `ws://${url}`; log(`Client connecting to ${address}`); const client = new ws_protocol_1.FoxgloveClient({ ws: new ws_1.default(address, [ws_protocol_1.FoxgloveClient.SUPPORTED_SUBPROTOCOL]), }); const deserializers = new Map(); client.on("error", (error) => { log("Error", error); throw error; }); client.on("advertise", (channels) => { for (const channel of channels) { if (channel.encoding === "json") { const textDecoder = new TextDecoder(); const subId = client.subscribe(channel.id); deserializers.set(subId, (data) => JSON.parse(textDecoder.decode(data))); } else if (channel.encoding === "protobuf") { const root = protobufjs_1.default.Root.fromDescriptor(descriptor_1.FileDescriptorSet.decode(Buffer.from(channel.schema, "base64"))); const type = root.lookupType(channel.schemaName); const subId = client.subscribe(channel.id); deserializers.set(subId, (data) => type.decode(new Uint8Array(data.buffer, data.byteOffset, data.byteLength))); } else { console.warn(`Unsupported encoding ${channel.encoding}`); } } }); client.on("message", ({ subscriptionId, timestamp, data }) => { console.log({ subscriptionId, timestamp, data: deserializers.get(subscriptionId)(data), }); }); } exports.default = new commander_1.Command("simple-client") .description("connect to a server and subscribe to all messages") .argument("[url]", "ws(s)://host:port", "ws://localhost:8765") .action(main); //# sourceMappingURL=simple-client.js.map