UNPKG

dbus-sdk

Version:

A Node.js SDK for interacting with DBus, enabling seamless service calling and exposure with TypeScript support

84 lines (83 loc) 3.11 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.DBusService = void 0; const DBusObject_1 = require("./DBusObject"); const xml2js_1 = require("xml2js"); const DBusTypeClass_1 = require("./lib/DBusTypeClass"); class DBusService { #uniqueName; get uniqueName() { return this.#uniqueName; } constructor(opts) { this.opts = opts; this.dbus = opts.dbus; this.name = opts.service; this.#uniqueName = opts.uniqueName; } /** * Update unique name * @param uniqueName * @protected */ updateUniqueName(uniqueName) { this.#uniqueName = uniqueName; } /** * List all object paths */ async listObjects() { if (!this.name) return []; const emptyObjectPaths = []; const getSubNodes = async (objectPath = '/') => { const objectPaths = objectPath === '/' ? ['/'] : []; const [xmlResponse] = await this.dbus.invoke({ service: this.name, objectPath: objectPath, interface: 'org.freedesktop.DBus.Introspectable', method: 'Introspect' }); if (!xmlResponse) return []; const parsedObject = await (0, xml2js_1.parseStringPromise)(xmlResponse instanceof DBusTypeClass_1.DBusTypeClass ? xmlResponse.value : xmlResponse); if (!parsedObject?.node?.interface) emptyObjectPaths.push(objectPath); if (!parsedObject?.node?.node) return []; const nodeNames = parsedObject.node.node.map((node) => node.$.name); const promises = []; nodeNames.forEach((nodeName) => { const fullObjectPath = `${objectPath === '/' ? '' : objectPath}/${nodeName}`; objectPaths.push(fullObjectPath); promises.push(new Promise(resolve => getSubNodes(`${objectPath === '/' ? '' : objectPath}/${nodeName}`).then(resolve).catch(() => resolve([])))); }); const result = await Promise.all(promises); result.forEach((item) => item.forEach((value) => objectPaths.push(value))); return objectPaths; }; const allObjectPaths = [...new Set(await getSubNodes())]; if (!allObjectPaths.includes('/')) allObjectPaths.push('/'); //将根路径加入列表 return allObjectPaths.concat(emptyObjectPaths).filter(v => !allObjectPaths.includes(v) || !emptyObjectPaths.includes(v)); } /** * Get all objects from dbus service */ async getObjects() { const objectPaths = await this.listObjects(); return Promise.all(objectPaths.map((objectPath) => this.getObject(objectPath))); } /** * Get object from dbus service * @param objectPath */ async getObject(objectPath) { return new DBusObject_1.DBusObject({ ...this.opts, objectPath: objectPath, dbusService: this }); } } exports.DBusService = DBusService;