@ecobridge.xyz/devicemanager
v4.12.0
Published
a device manager for talking to devices on network and over usb
Readme
@ecobridge.xyz/devicemanager
A comprehensive, TypeScript-first device manager for discovering and communicating with network devices. 🔌
🎯 Overview
@ecobridge.xyz/devicemanager provides a unified, object-oriented API for discovering and modeling network devices, with live communication where protocol implementations are available. Whether you're building a document scanning workflow, managing printers, controlling smart home devices, or monitoring UPS systems — this library has you covered.
Supported Device Types:
- 🖨️ Scanners — Brother native network scanning, eSCL (AirScan), and SANE
- 📄 Printers — IPP/AirPrint discovery, capabilities, jobs, cancellation, and print execution; JetDirect/raw port detection
- 📁 SMB Shares — Host local folders through smartsamba and emit settled document arrivals through RxJS
- 🧊 3D Printers — Bambu Lab (LAN Only Mode + Developer Mode), Klipper via Moonraker, OctoPrint and PrusaLink: discovery, live status, upload and print, pause/resume/stop
- 🔊 Speakers — Sonos, AirPlay, Chromecast, and DLNA discovery; live transport and volume control over UPnP for Sonos and DLNA, plus announcements that interrupt and restore playback
- 🔋 UPS Systems — NUT, SNMP protocols
- 📡 SNMP Devices — Community-based SNMP v1 and v2c sessions; v3 is not implemented
- 🏠 Smart Home — Home Assistant integration (lights, switches, sensors, climate, locks, fans, cameras, covers)
Issue Reporting and Security
For reporting bugs, issues, or security vulnerabilities, please visit community.foss.global/. This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a code.foss.global/ account to submit Pull Requests directly.
📦 Installation
The published package includes the SNMP and WebSocket type dependencies used by its declarations. TypeScript consumers do not need to install @types/net-snmp or @types/ws separately.
The device service binary comes in a separate package per platform, which this package lists as optional dependencies: @ecobridge.xyz/devicemanager-linux-x64 and @ecobridge.xyz/devicemanager-linux-arm64 (static musl builds, which run on glibc and musl systems alike), @ecobridge.xyz/devicemanager-darwin-x64 and @ecobridge.xyz/devicemanager-darwin-arm64. Package managers install only the one matching the host. On a platform without a package, or when optional dependencies are omitted (--no-optional, --omit=optional), the device service cannot start and fails with ERR_DEVICE_SERVICE_UNAVAILABLE; there is no fallback. DeviceManager.startDiscovery() then discovers through SSDP and the Bambu listener only (see mDNS Service Types).
# Using pnpm (recommended)
pnpm add @ecobridge.xyz/devicemanager
# Using npm
npm install @ecobridge.xyz/devicemanager
# Using yarn
yarn add @ecobridge.xyz/devicemanager🚀 Quick Start
The OOP Pattern: Discovery → Selection → Feature → Operation
import { DeviceManager, ScanFeature } from '@ecobridge.xyz/devicemanager';
import * as fs from 'fs/promises';
async function scanDocument() {
const manager = new DeviceManager();
// 1️⃣ DISCOVERY - Find scanners in your network
await manager.discoverScanners('192.168.1.0/24');
// 2️⃣ INSPECTION - See what's available
const scanners = manager.getDevices({ hasFeature: 'scan' });
console.log('Found scanners:', scanners.map(s => `${s.name} at ${s.address}`));
// 3️⃣ SELECTION - Choose your device (explicit, no magic!)
const device = manager.selectDevice({ address: '192.168.1.100' });
// 4️⃣ FEATURE ACCESS - Get the capability you need
const scanFeature = device.selectFeature<ScanFeature>('scan');
// 5️⃣ OPERATION - Do the thing!
await scanFeature.connect();
const result = await scanFeature.scan({
source: 'flatbed',
resolution: 300,
colorMode: 'color',
format: 'jpeg',
});
await fs.writeFile('scan.jpg', result.data);
console.log(`Saved: scan.jpg (${result.data.length} bytes)`);
await manager.shutdown();
}
scanDocument();🏗️ Architecture
The library follows a clean, composable architecture:
┌─────────────────────────────────────────────────────────────┐
│ DeviceManager │
│ • Discovery (mDNS, SSDP, Network Scanning) │
│ • Device Registry (by IP, deduplication) │
│ • Device Selection (query & assert patterns) │
└─────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ UniversalDevice │
│ • Represents any network device │
│ • Composable features (scan, print, volume, etc.) │
│ • Connection lifecycle management │
└─────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ Features │
│ ScanFeature │ PrintFeature │ PlaybackFeature │ VolumeFeature
│ PowerFeature │ SnmpFeature │ LightFeature │ SwitchFeature │
│ SensorFeature │ ClimateFeature │ CameraFeature │ ... │
└─────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ Protocols │
│ Brother Scan │ eSCL │ SANE │ IPP │ SNMP │ NUT │ UPnP/SOAP │
└─────────────────────────────────────────────────────────────┘📖 API Reference
DeviceManager
The central orchestrator for device discovery and management.
const manager = new DeviceManager({
discoveryTimeout: 10000, // Discovery timeout in ms
enableRetry: true, // Enable retry with exponential backoff
maxRetries: 5, // Maximum retry attempts
});Constructing DeviceManager does not initiate network discovery. Call startDiscovery() explicitly when continuous mDNS/SSDP discovery (and the Bambu Lab announcement listener on UDP 2021/1990) should begin; the autoDiscovery option does not currently trigger startup.
Discovery Methods
// Focused scanner discovery
const scanners = await manager.discoverScanners('192.168.1.0/24', {
timeout: 3000,
concurrency: 50,
});
// Focused printer discovery
const printers = await manager.discoverPrinters('192.168.1.0/24');
// General network scan (all device types)
const devices = await manager.scanNetwork({
ipRange: '192.168.1.0/24',
probeBrother: true,
probeEscl: true,
probeIpp: true,
probeSane: true,
probeAirplay: true,
probeSonos: true,
probeChromecast: true,
});
// mDNS/SSDP continuous discovery
await manager.startDiscovery();
manager.on('device:found', ({ device, featureType }) => {
console.log(`Found: ${device.name}`);
});
await manager.stopDiscovery();Device Selection
// Query pattern (returns array, may be empty)
const allDevices = manager.getDevices();
const scanners = manager.getDevices({ hasFeature: 'scan' });
const brotherDevices = manager.getDevices({ name: 'Brother' });
// Assert pattern (returns single device, throws if not found)
const device = manager.selectDevice({ address: '192.168.1.100' });
const scanner = manager.selectDevice({ name: 'Brother', hasFeature: 'scan' });IDeviceSelector Interface
interface IDeviceSelector {
id?: string; // Exact match on device ID
address?: string; // Exact match on IP address
hardwareId?: string; // Exact match on the device's own identity (any case, with or without urn:uuid:)
name?: string; // Partial match (case-insensitive)
model?: string; // Partial match (case-insensitive)
manufacturer?: string; // Partial match (case-insensitive)
hasFeature?: TFeatureType; // Must have this feature
hasFeatures?: TFeatureType[]; // Must have ALL features
hasAnyFeature?: TFeatureType[]; // Must have ANY feature
}UniversalDevice
Represents any network device with composable features.
const device = manager.selectDevice({ address: '192.168.1.100' });
// Device properties
console.log(device.name); // "Brother MFC-J5730DW"
console.log(device.address); // "192.168.1.100"
console.log(device.manufacturer); // "Brother"
console.log(device.model); // "MFC-J5730DW"
console.log(device.status); // 'online' | 'offline' | 'busy' | 'error'
console.log(device.hardwareId); // "e3248000-80ce-11db-8000-30055c773bcf" or undefined
console.log(device.makeAndModel); // "Brother MFC-J5730DW" once a scan or print feature connected
// Feature access (safe query - returns undefined)
const maybeScan = device.getFeature<ScanFeature>('scan');
// Feature access (assert - throws if not available)
const scanFeature = device.selectFeature<ScanFeature>('scan');
// The device's own identity: the UUID of its mDNS advertisement, else what a
// connected scan or print feature read (eSCL capabilities, IPP printer-uuid).
// Unlike `id` (`<address>:<port>`) it stays the same when the device gets
// another address; keep it to find the device again.
const again = manager.selectDevice({ hardwareId: device.hardwareId });
// What the device says it is, read when a scan or print feature connects:
// `makeAndModel` from eSCL MakeAndModel or IPP printer-make-and-model, and
// `manufacturer`/`model` from an IPP printer's printer-device-id where
// discovery named none. A device added by address alone gets them this way,
// and selectDevice({ manufacturer, model }) matches them. What discovery names
// comes first, whether it arrives before or after a feature connected.
// The connected feature carries the same three values.
// Check capabilities
device.hasFeature('scan'); // true/false
device.hasFeatures(['scan', 'print']); // must have ALL
device.hasAnyFeature(['scan', 'print']); // must have ANY
device.getFeatureTypes(); // ['scan', 'print', ...]Features
🖨️ ScanFeature
const scanFeature = device.selectFeature<ScanFeature>('scan');
await scanFeature.connect();
// Get capabilities
const caps = await scanFeature.getCapabilities();
// { resolutions: [100, 200, 300, 600], formats: ['jpeg', 'png', 'pdf'], ... }
// Scan a document
const result = await scanFeature.scan({
source: 'flatbed', // 'flatbed' | 'adf' | 'adf-duplex'
resolution: 300, // DPI
colorMode: 'color', // 'color' | 'grayscale' | 'blackwhite'
format: 'jpeg', // 'jpeg' | 'png' | 'pdf' | 'tiff'
quality: 85, // JPEG quality (1-100)
area: { x: 0, y: 0, width: 210, height: 297 }, // mm
});
// result.data is a Buffer containing the scanned image
await fs.writeFile('scan.jpg', result.data);
// ADF scans expose every returned document. `data` remains the first document
// for backwards compatibility. Use `pages` to avoid dropping later sheets/sides.
console.log(`Scanner returned ${result.pageCount} document(s)`);
for (const [index, page] of (result.pages ?? []).entries()) {
await fs.writeFile(`scan-${index + 1}.jpg`, page.data);
}If a scanner times out or cancels after transferring one or more documents,
EsclScanError.partialResult contains those documents with isComplete: false.
Callers can persist partialResult.pages before deciding whether to retry.
Some scanner firmware accepts eSCL settings but returns a different format or
resolution. Check result.settingsWarnings before treating the requested scan
quality as confirmed.
Brother devices discovered on TCP 54921 use the native scan transport before
eSCL. It explicitly selects AUTO for ADF input, controls simplex/duplex, and
rejects a lease when the device does not grant the requested resolution. The
native transport currently returns color JPEG pages; unsupported output formats
or color modes fail explicitly instead of being silently substituted.
Duplex-capable scanners default to adf-duplex; callers can still request
adf or flatbed explicitly. The transport preserves every returned side.
Blank-page classification and removal belong in consuming applications, where
document-specific review rules can be applied.
📄 PrintFeature
PrintFeature.print() submits jobs through IPP, the print transport used by
AirPrint. It reads printer capabilities, submits jobs, reports job state, and
supports cancellation. Network discovery can also identify an open
JetDirect/raw port at TCP 9100, but JetDirect print execution is not implemented.
const printFeature = device.selectFeature<PrintFeature>('print');
await printFeature.connect();
// Get printer capabilities
const caps = await printFeature.getCapabilities();
console.log(caps.airPrintSupported, caps.documentFormats, caps.resolutions);
// Print a document
const job = await printFeature.print(pdfBuffer, {
copies: 2,
mediaSize: 'iso_a4_210x297mm',
sides: 'two-sided-long-edge',
quality: 'high',
colorMode: 'color',
jobName: 'My Document',
});
// Get current job information
const jobInfo = await printFeature.getJobInfo(job.id);print() sends a document in the format its bytes show (PDF, JPEG, PNG, TIFF,
PostScript, PWG Raster, Apple Raster) if the printer takes that format, and
refuses it otherwise; it does not convert documents.
Printers without PDF: raster pages
Many printers take no PDF, only raster pages: PWG Raster (image/pwg-raster,
IPP Everywhere) or Apple Raster (image/urf, AirPrint). printRaster() prints
a document given as pages of pixels on such a printer. getRasterTarget()
says how to render the pages: the format the printer takes (PWG Raster before
Apple Raster), a resolution it takes (300 dpi or the next above it; the lowest
for quality: 'draft', the highest for 'high'), and RGB or gray (gray for
colorMode: 'monochrome', a printer without color, or one that takes only
gray). The pages are encoded as they come and sent as one job, so copies and
two-sided printing apply to the whole document, and the back of every
two-sided sheet is turned as the printer asks (pwg-raster-document-sheet-back,
URF DM1–DM4). @push.rocks/smartpdf's rasterizePdfPages renders a PDF to
pages of exactly this shape, one page at a time:
const target = printFeature.getRasterTarget({ colorMode: 'monochrome' });
if (target) {
const pages = smartPdf.rasterizePdfPages(pdfBuffer, { dpi: target.dpi, colorSpace: target.colorSpace, intent: 'print' });
const job = await printFeature.printRaster(pages, { colorMode: 'monochrome', sides: 'two-sided-long-edge' });
}The encoders are exported too: encodeRasterDocument(pages, target, options)
writes a PWG Raster or Apple Raster document, rasterCapabilitiesOf() reads
what a printer takes from its IPP attributes, and chooseRasterTarget() picks
the target.
🧊 Print3dFeature (3D printers)
Print3dFeature is the 3D printer counterpart to the IPP print feature. It
uploads sliced files, starts, pauses, resumes and stops jobs, and streams live
status. One protocol-neutral API covers four printer families:
| Protocol | Discovery | Credentials | Upload formats | Live status |
|----------|-----------|-------------|----------------|-------------|
| bambu — Bambu Lab (LAN Only Mode + Developer Mode) | SSDP NOTIFY broadcasts on UDP 2021/1990 | serial + LAN access code | .gcode.3mf | MQTT push over TLS (8883) |
| moonraker — Klipper | mDNS _moonraker._tcp (only with [zeroconf] in moonraker.conf) | API key, or none for trusted_clients | .gcode, .g, .gco | WebSocket printer.objects.subscribe |
| octoprint — OctoPrint | mDNS _octoprint._tcp | API key | .gcode, .gco, .g | push socket /sockjs/websocket |
| prusalink — Prusa (Buddy firmware, PrusaLink on a Pi) | mDNS _prusalink._tcp | printer password (Digest, user maker) or API key | .gcode, plus .bgcode on firmware 5.1+ | polling /api/v1/status (PrusaLink has no push channel) |
Discovery never carries credentials and broadcasts do not cross subnets.
Discovered printers are listed with their identity; addPrint3dPrinter()
supplies the credentials (or adds a printer by address), replaces any print3d
feature already registered for that address, and connects it.
import { DeviceManager, Print3dFeature, Print3dProtocolError } from '@ecobridge.xyz/devicemanager';
const manager = new DeviceManager();
manager.on('device:found', ({ device, featureType }) => {
if (featureType === 'print3d') console.log(device.name, device.model, device.serialNumber, device.address);
});
await manager.startDiscovery();
// The user picked a printer and entered its access code.
const device = await manager.addPrint3dPrinter({
protocol: 'bambu',
host: '192.168.5.40',
serial: '00M09A350100123',
accessCode: '12345678',
});
const printer = device.selectFeature<Print3dFeature>('print3d');
console.log(printer.identity); // model, serialNumber, firmwareVersion, host
console.log(printer.capabilities); // fileFormats, buildVolume, camera, filamentSlotCount
printer.status$.subscribe((status) => {
// state: idle | preparing | printing | paused | finished | cancelled | error | offline
console.log(status.state, status.progressPercent, status.currentLayer, status.totalLayers,
status.remainingSeconds, status.nozzle, status.bed, status.jobName, status.errors, status.filamentSlots);
});
try {
await printer.print(sliced3mf, { fileName: 'bracket.gcode.3mf', bambu: { plate: 1, useAms: true, amsMapping: [0] } });
} catch (error) {
if (error instanceof Print3dProtocolError && error.code === 'developer-mode-required') {
console.error(error.printerMessage, error.printerCode); // e.g. 'mqtt message verify failed', 84033543
}
}
await printer.pause();
await printer.resume();
await printer.stop();The other protocols take their own options, for example
{ protocol: 'moonraker', host: 'voron.local' },
{ protocol: 'octoprint', host: 'octopi.local', apiKey } or
{ protocol: 'prusalink', host: '192.168.5.60', password }.
Without a device manager, createPrint3dPrinter(options) builds a device and
createPrint3dController(options) returns the bare protocol controller
(BambuProtocol, MoonrakerProtocol, OctoPrintProtocol, PrusaLinkProtocol).
status$replays the latest status and stays open across reconnects; the feature also emitsprint3d:status,print3d:state,print3d:uploaded,print3d:started,print3d:paused,print3d:resumed,print3d:stoppedandprint3d:deleted.refreshStatus()reads a fresh status.upload()stores a file without starting it;print()uploads and starts it;deleteFile()removes an uploaded file.- Live connections reconnect with backoff (1 s to 30 s) and report
offlinewhile the printer is unreachable. - Every failure is a
Print3dProtocolErrorwithprotocol,code(auth-failed,developer-mode-required,command-rejected,unsupported-format,tls-verification,not-connected,invalid-options,invalid-response,http,transport,timeout,cancelled,closed),effectOutcome(not-sent,rejected,indeterminate) and the printer's ownprinterMessage/printerCode/httpStatuswhere it returned one. Onlytransportandtimeoutare retried byconnect().
Bambu Lab: LAN Only Mode and Developer Mode
Since the Authorization Control firmware (X1 series 01.08.03.00 and later,
January 2025), Bambu printers accept job commands from LAN clients only in
Developer Mode. On the printer, enable LAN Only Mode first, then
Developer Mode (see the Bambu Lab wiki article "Enable Developer Mode"). The
printer then no longer connects to Bambu Cloud. Without Developer Mode,
status reading still works, but print(), pause(), resume() and stop() are
refused: the error code is developer-mode-required and printerMessage /
printerCode carry the printer's reply, e.g. "mqtt message verify failed" /
84033543, or HMS 0500_0500_0001_0007 on P1/A1 firmware.
BambuProtocol.developerMode reads the mode from the report's fun field
where the printer sends it (not on P1/A1).
How the Bambu protocol talks to the printer:
- Status — MQTT over TLS on 8883, user
bblp, password = access code, subscribed todevice/<serial>/report. A full report (pushall) is requested on connect; later reports are merged (P1/A1 send only changed fields).readStatus()requests a full report at most every 3 s, and at most every 5 minutes on P1/A1, as Bambu recommends. - Upload — implicit FTPS on 990 to the storage root. The printer requires every data connection to resume the control connection's TLS session; the client does that.
- Print —
project_fileforMetadata/plate_<n>.gcodeof the uploaded.gcode.3mf, addressed asfile:///sdcard/<name>(X1, P1, A1 series) orftp:///<name>(H2 series);bambu.fileUrloverrides this. Job options:plate,useAms(default: the printer reports an AMS),amsMapping(default[0]),bedLevelling(default on),flowCalibration,vibrationCalibration,timelapse(default off). - Commands — published at QoS 1. An echo with
result: successconfirms a command; an echo witherr_code/result: failed, or the verification HMS, rejects it. Many firmware versions acknowledge only through the next status report, so without an echo a command counts as delivered aftercommandAckMs(default 5 s). - Certificate verification — the printer certificate's chain must end in
one of Bambu Lab's printer CAs (bundled as
BAMBU_CA_CERTIFICATES, from ha-bambulab) and its common name must equal the serial; TLS is capped at 1.2.tls: { mode: 'bambu-ca', additionalCa }adds CAs,tls: { mode: 'ca', ca }replaces them. There is no mode that accepts any certificate. - Discovery —
BambuDiscoverylistens on UDP 2021 and 1990 (with address reuse, next to Bambu Studio or OrcaSlicer) for NOTIFY packets with NTurn:bambulab-com:device:3dprinter:1and admits only announcements whoseLocationequals the sender.DeviceManager.startDiscovery()runs it; when a printer announces a new address, its unconnected entry at the old address is dropped (device:lost, orfeature:removedwhen that device has other features).
Bambu Connect and the Bambu cloud API are not used: this package implements only the direct LAN path with Developer Mode.
📁 SMB Share Provider
DeviceManager.provideSmbShares() hosts one or more local folders with
@push.rocks/smartsamba. The provider waits until a new file has stopped
changing before it emits document:arrived, which keeps consumers from opening
a scan while the sending device is still writing it.
import { DeviceManager } from '@ecobridge.xyz/devicemanager';
const manager = new DeviceManager({ autoDiscovery: false });
const provider = await manager.provideSmbShares({
host: '0.0.0.0',
port: 445,
users: [{
username: 'scanner',
password: process.env.SMB_SCANNER_PASSWORD!,
}],
shares: [{
name: 'scans',
path: '/srv/device-scans',
users: [{ username: 'scanner', access: 'readWrite' }],
}],
settleTimeMs: 1000,
});
const subscription = provider.documents$.subscribe((document) => {
console.log(`New document: ${document.shareName}/${document.relativePath}`);
});
// The same event is forwarded through the manager as smb:document:arrived.
const managerSubscription = manager.events$.subscribe((event) => {
if (event.name === 'smb:document:arrived') {
console.log(event.args[0]);
}
});
// Later:
subscription.unsubscribe();
managerSubscription.unsubscribe();
await manager.shutdown();The provider recursively monitors every configured share. It also emits
document:changed, document:removed, started, stopped, and
provider:error. Existing files are treated as the startup baseline unless
emitExistingDocuments is enabled.
Binding SMB's standard TCP port 445 can require elevated privileges. Published
smartsamba 0.3.1 packages support signed SMB 2.0.2 and 2.1 clients and include
Linux amd64 and arm64 engines. Other platforms can provide a locally built engine
through SMARTSAMBA_RUST_BINARY.
Do not store SMB passwords in device metadata or log provider options.
Yeelight LAN control
probeYeelight() uses the documented vendor discovery exchange on multicast
port 1982. Select the local IPv4 interface explicitly; the probe admits only the
requested bulb address and optional expected device ID. Its deadline and
AbortSignal cover discovery and socket cleanup. No URL fetch, DNS lookup or
automatic TCP connection follows discovery.
import { probeYeelight, YeelightProtocol, YeelightError } from '@ecobridge.xyz/devicemanager';
const advertisement = await probeYeelight({
address: '192.168.1.20',
localAddress: '192.168.1.10',
expectedId: '0x000000000015243f',
timeoutMs: 5000,
});
const bulb = new YeelightProtocol({
address: advertisement.address,
port: advertisement.port,
supportedMethods: advertisement.supportedMethods,
});
const unsubscribe = bulb.subscribeProperties((properties) => {
console.log(properties);
});
try {
await bulb.connect();
const properties = await bulb.getProperties(['power', 'bright', 'rgb']);
await bulb.setPower(true);
await bulb.setBrightness(50, { effect: 'smooth', durationMs: 350 });
if (advertisement.supportedMethods.includes('set_rgb')) await bulb.setRgb(0xff0000);
} catch (error) {
if (error instanceof YeelightError) {
console.error(error.code, error.effectOutcome);
}
throw error;
} finally {
unsubscribe();
await bulb.close();
}Enable LAN Control in the Yeelight app first. These are unauthenticated,
unencrypted LAN identifiers and capabilities; matching a discovery ID does not
cryptographically authenticate a device. Choose the home, endpoint and interface
from trusted application configuration. TCP does not expose a documented device
ID or supported-method property, so do not infer either from getProperties().
The client owns one terminal connection with exact request IDs, strict UTF-8 JSON and CRLF framing. It never retries or reconnects. It defaults to 5-second connection, request and incomplete-frame deadlines, 64-KiB frames, 32 pending requests and 32 subscriptions. Options can raise frame bounds to 1 MiB and pending/subscription bounds to 128. The rolling per-connection quota is 60 commands per minute; capacity and quota errors refuse admission before sending. Queued TCP write bytes are capped by the configured frame bound too. The bulb's documented total LAN quota spans other clients too; this instance cannot coordinate their command traffic.
Controls accept boolean power, integer brightness 1–100 and packed integer RGB
0–16777215. Smooth transitions require at least 30 ms; invalid values reject
without clamping. Only advertised methods can be sent. Scenes, colour flows,
music mode, background-channel controls and arbitrary commands are outside this
API. A matching ok acknowledges the command protocol; authoritative state comes
from getProperties() or props notifications. A control failure reports
not-sent, rejected or indeterminate; a missing acknowledgement after dispatch
is indeterminate and must be reconciled before a caller considers another effect.
Reads use not-sent because they dispatch no physical effect.
connect() accepts startup cancellation and a deadline; its signal is released
when startup settles. Every request accepts its own signal/deadline. close()
settles active requests, removes subscriptions/timers, destroys the owned TCP
socket and waits for cleanup. It permanently refuses new requests and reconnects.
Each subscription has independent disposal. A throwing subscription terminates
the connection and is observable through lastError with code callback-error.
Protocol reference: Yeelight WiFi Light Inter-Operation Specification. LAN setup: Yeelight LAN Control instructions.
🔊 PlaybackFeature & VolumeFeature
PlaybackFeature and VolumeFeature provide normalized capability and state models, backed by a protocol controller when one is available.
Sonos and DLNA renderers are driven over UPnP SOAP: the factories and DeviceManager
attach a UpnpPlaybackController (AVTransport) and UpnpVolumeController
(RenderingControl), so these calls reach the real device. AirPlay and Chromecast have
no bundled protocol client, so for those the same methods only update local feature
state and emit events.
const playback = device.selectFeature<PlaybackFeature>('playback');
const volume = device.selectFeature<VolumeFeature>('volume');
await playback.connect(); // primes cached state from the device
// Transport control — real AVTransport SOAP calls on Sonos/DLNA
await playback.play('http://example.com/audio.mp3');
await playback.pause();
await playback.stop();
await playback.seek(120); // seconds, sent as a REL_TIME target
// Live status, read back from the device
const status = await playback.getPlaybackStatus();
// { state: 'playing', position: 65, duration: 260, track: { title, artist, album, ... } }
// Volume — real RenderingControl SOAP calls on Sonos/DLNA
await volume.setVolume(50); // 0-100, clamped to the feature range
await volume.setMute(true);
await volume.toggleMute();
const level = await volume.getVolume();A failed command rejects rather than reporting a false success, and the cached state is left untouched when the device refuses.
Drive the protocol directly when you do not need the device model:
import { UpnpPlaybackController, UpnpVolumeController } from '@ecobridge.xyz/devicemanager';
const playback = UpnpPlaybackController.forSonos('192.168.1.52');
await playback.play();
const volume = UpnpVolumeController.forSonos('192.168.1.52');
await volume.setVolume(35);Sonos grouping and zones (ZoneGroupTopology, GroupRenderingControl), the queue,
favorites, alarms and EQ are not implemented, and there is no GENA event subscription —
status is read on demand rather than pushed.
UpnpSoapClient(baseUrl, { timeoutMs, maxResponseBytes, abortSignal }) owns its request
lifetime. Defaults are 10 seconds and 1 MiB per response. SOAP methods and controller
methods accept an optional final AbortSignal; getXml(path, signal) applies the same
limits to device and service descriptions. Requests remain on the configured HTTP(S)
origin, reject redirects, and retain their deadline while reading the response body.
await client.close() aborts and drains requests and prevents reuse. Controllers also
expose close(); closing a controller cancels its own work and closes its client only
when it created that client. An injected shared client remains owned by its caller.
SOAP parsing validates the envelope, namespace and action response, including faults
returned with HTTP 200. UpnpSoapFault exposes the action, HTTP status, error code and
description. Missing, duplicate, malformed or invalid typed outputs fail rather than
becoming a stopped player, zero volume or unmuted state. Volume writes require an
integer from 0 to 100. parseXml, extractValues and extractOptionalValues provide
the same bounded XML validation for vendor descriptions and metadata; values are
strings, CDATA is preserved, and entities are decoded once. DTDs and nesting beyond
64 elements are rejected.
client.generateDidlMetadata(title, url, mimeType?) creates DIDL-Lite metadata for
setAVTransportURI. Audio MIME identifiers such as audio/mpeg select
object.item.audioItem, with case-insensitive type matching. The default remains
video/mp4 with object.item.videoItem; other MIME types retain the video class.
Pass a bare type/subtype identifier with names of at most 127 characters each;
parameters, wildcards and malformed identifiers are rejected. Titles and URLs must
contain valid XML 1.0 text. The helper escapes title, URL and protocolInfo attribute
values; pass its result directly to setAVTransportURI, which escapes the metadata
once more for the outer SOAP document.
📢 Announcements
SpeakerAnnouncer plays a short clip on a speaker and restores whatever it interrupted.
A UPnP renderer fetches audio rather than accepting a push, so the clip is published on a
local HTTP server (ClipServer) and the speaker is pointed at that URL.
import { SpeakerAnnouncer } from '@ecobridge.xyz/devicemanager';
const announcer = new SpeakerAnnouncer();
await announcer.start();
await announcer.announceOnSonos('192.168.1.52', { data: wavBuffer }, { volume: 35 });
await announcer.stop();The announcement snapshots the transport URI, position and volume, plays the clip, then puts everything back — resuming only if the speaker was playing beforehand. Restore also runs when the announcement fails, so a broken clip never strands the speaker on a dead URL at announcement volume.
No speech engine is bundled. Supply any synthesizer through the ISpeechSynthesizer
interface to use announceText():
const announcer = new SpeakerAnnouncer({
synthesizer: {
synthesize: async (text) => ({ data: await myTts(text), contentType: 'audio/wav' }),
},
});
await announcer.announceText('192.168.1.52', 'Front door open');Audio must be something the renderer decodes; 44.1 kHz mono 16-bit WAV is a safe default.
ClipServer sets Content-Type and Content-Length and answers HEAD and Range
requests, though Sonos issues neither for short clips.
Announcements must target the group coordinator. Bonded satellites — home-theatre surrounds and subs — have no transport of their own and reject transport commands, while still accepting volume changes.
🔋 PowerFeature (UPS)
const power = device.selectFeature<PowerFeature>('power');
await power.connect();
// Get UPS status
const status = await power.getStatus();
// 'online' | 'onbattery' | 'lowbattery' | ... | 'unknown'
// Get battery info
const battery = await power.getBatteryInfo();
// { charge: 0, runtime: 0 } until a protocol-specific implementation updates it
// Run a battery test when supported
if (power.supportsTest) {
await power.testBattery();
}🏠 Smart Home Features
// Light control
const light = device.selectFeature<LightFeature>('light');
await light.turnOn();
await light.setBrightness(80); // 0-255
await light.setRgbColor(255, 100, 50);
await light.setColorTemp(4000); // Kelvin
// Switch control
const switch_ = device.selectFeature<SwitchFeature>('switch');
await switch_.turnOn();
await switch_.turnOff();
await switch_.toggle();
// Climate control
const climate = device.selectFeature<ClimateFeature>('climate');
await climate.setTargetTemp(22);
await climate.setHvacMode('heat'); // 'heat' | 'cool' | 'auto' | 'off'
// Sensor reading
const sensor = device.selectFeature<SensorFeature>('sensor');
const reading = await sensor.refreshState();
// { value: 22.5, numericValue: 22.5, unit: '°C', lastUpdated: Date }
// Cached accessors reflect the most recently fetched or externally updated state
console.log(sensor.value, sensor.numericValue, sensor.unit, sensor.lastUpdated);Protocol Direct Access
For advanced use cases, you can access protocols directly:
import { EsclProtocol, IppProtocol, SnmpProtocol } from '@ecobridge.xyz/devicemanager';
// Direct eSCL (AirScan) access
const escl = new EsclProtocol('192.168.1.100', 80, false);
const caps = await escl.getCapabilities();
const result = await escl.scan({ source: 'flatbed', resolution: 300 });
// Direct IPP access
const ipp = new IppProtocol('192.168.1.100', 631, '/ipp/print');
const printerAttrs = await ipp.getPrinterAttributes();
// Direct SNMP access
const snmp = new SnmpProtocol('192.168.1.100', { community: 'public' });
const sysDescr = await snmp.get('1.3.6.1.2.1.1.1.0');Tuya 3.4 Local Protocol
TuyaProtocol opens one explicitly configured LAN session for a mains-powered Tuya
device with local protocol 3.4. It authenticates frames with HMAC-SHA256 and
negotiates a fresh AES session key. Other protocol versions, cloud-only devices,
sleeping battery devices and gateway sub-devices are unsupported. It does not
discover credentials or guess a product's datapoint IDs.
import { TuyaProtocol, TuyaProtocolError } from '@ecobridge.xyz/devicemanager';
// Supply the device's actual 16-byte local key from your encrypted secret store.
const client = new TuyaProtocol({
deviceId: configuredDeviceId,
localKey: configuredLocalKeyBytes,
host: '192.168.1.50',
version: '3.4',
});
const unsubscribe = client.subscribe((report) => {
// Only datapoints reported by this authenticated session update the cache.
console.log(report.datapoints);
});
try {
await client.connect();
const snapshot = await client.queryDatapoints();
console.log(snapshot.datapoints);
// Select a writable datapoint from this product's verified schema.
const receipt = await client.setDatapoints({[configuredSwitchDatapointId]: true});
console.log(receipt.outcome); // 'acknowledged': protocol acceptance
} catch (error) {
if (error instanceof TuyaProtocolError && error.effectOutcome === 'indeterminate') {
// The write may have reached the device; do not automatically repeat it.
console.log('Inspect authoritative device state before another operation.');
} else throw error;
} finally {
unsubscribe();
await client.close();
}queryDatapoints(signal?) requires an authenticated STATUS reply with the query's
sequence. setDatapoints(datapoints, signal?) requires a matching CONTROL_NEW ACK;
an unrelated state push cannot complete it. Some firmware does not echo a command's
sequence; that firmware fails the operation deadline and needs a separately verified
protocol contract. ACKs establish protocol acceptance, and physical completion is
observed through subsequent reports. Writes never update cached state optimistically.
TuyaProtocolError exposes code, sequence, optional returnCode, and
effectOutcome: not-sent, indeterminate after a transmission attempt, or
rejected for an explicit correlated device rejection. No effect is automatically
retried and no connection is automatically recreated. close() is permanent,
idempotent, rejects pending operations and joins socket shutdown. Use a new instance
for a new session. Caller-owned key bytes are copied, and the engine clears its key
copies on termination. Errors omit credential and raw payload contents.
Options default to TCP port 6668, a 5-second total connect deadline, a 5-second request deadline, a 10-second heartbeat interval, 64 KiB maximum frames and 16 concurrent caller requests. One additional heartbeat slot keeps health checks independent of caller saturation. Hosts must be literal IPv4 private/link-local/ loopback or IPv6 local/loopback addresses. Datapoint maps contain 1–255 IDs in the range 1–255, with boolean, safe-integer or bounded string values. Nested/raw values, accessors, duplicate JSON properties and unsupported response identities fail closed.
connected, immutable datapoints, lastError and subscribeErrors() expose
session health. Subscribers run synchronously and must not block. Async work started
by a subscriber remains caller-owned; rejected subscriber promises are reported
without interrupting receive processing. A lifetime abortSignal in the options
closes the entire session; method signals cancel only their own pending operation.
The Tuya product schema model is described in the vendor's DP Model and Control Protocol. LAN framing is documented by the original TinyTuya protocol implementation. This implementation has encrypted loopback fixture coverage; real device firmware qualification remains required for each product.
Legacy Kasa relay protocol
KasaProtocol owns the legacy TP-Link IOT XOR TCP transport, using an explicit unicast IP address and port 9999 by default. Its supported subset is a single relay advertised by IOT.SMARTPLUGSWITCH: plugs and switches with relay_state equal to 0 or 1. Multi-outlet strips, bulbs, dimmer settings, energy meters, schedules, Tapo, SMART/AES/KLAP, discovery broadcasts, and cloud login are outside this API. It accepts no credentials and performs no authentication; the device identity check binds operations to the observed legacy endpoint, not to a cryptographically authenticated peer.
import { KasaProtocol, KasaProtocolError } from '@ecobridge.xyz/devicemanager';
const kasa = new KasaProtocol({
host: '192.168.1.40',
expectedDeviceId: '800611223344556677889900AABBCCDDEEFF001122',
timeoutMs: 5000,
});
try {
const device = await kasa.getSystemInfo();
console.log(device.alias, device.powerState, device.capabilities);
const acknowledgment = await kasa.setPowerState(device.deviceId, true);
console.log(acknowledgment.acknowledgment); // Protocol acceptance only.
console.log(await kasa.getPowerState()); // A fresh authoritative query.
} catch (error) {
if (error instanceof KasaProtocolError) {
console.error(error.code, error.effectOutcome);
} else {
throw error;
}
} finally {
await kasa.close();
}getSystemInfo() returns immutable identity, model, versions, MAC, power state, and a power capability. The first successful query pins the device ID when expectedDeviceId is omitted. setPowerState(deviceId, boolean) revalidates that identity and capability on the same TCP connection before the relay request. It returns an immutable IKasaPowerAcknowledgment with physicalStateConfirmed: false; it does not mutate a cached state. Each method accepts { abortSignal }.
Each client serializes a bounded FIFO: maxPendingOperations defaults to 16 (maximum 128), including active work. timeoutMs covers admission, queueing, connection, identity preflight, and response, defaults to 5000, and is bounded to 1–30000 ms. maxResponseBytes defaults to 65536 and is bounded to 128–1048576. Responses require a bounded unsigned length, valid UTF-8/JSON without duplicate keys, and the exact requested system method. No command is retried or automatically reconnected.
KasaProtocolError.effectOutcome is not-sent before relay dispatch, rejected for a valid device error, and indeterminate when a relay may have been dispatched without a valid acknowledgment. KasaDeviceError also exposes the method and numeric device error code. Diagnostics omit raw device content. close() is terminal and idempotent: it rejects queued work, cancels active work, and waits for owned sockets to close. A constructor abortSignal closes the client for its entire lifetime.
Wire behavior was verified against the published TP-Link client and python-kasa XOR transport. Tests use local encrypted TCP fixtures; physical-device behavior remains unverified.
LIFX LAN Lighting
LifxProtocol binds one explicit unicast IPv4 endpoint and six-byte device MAC to
a bounded, serialized UDP client. It does not discover devices or change an endpoint
from incoming traffic. The LIFX LAN protocol is unauthenticated; matching a MAC and
UDP sender does not provide cryptographic device authentication.
import { LifxProtocol, LifxProtocolError } from '@ecobridge.xyz/devicemanager';
const light = new LifxProtocol({
host: '192.168.1.42',
macAddress: 'd073d5001337',
port: 56700,
timeoutMs: 5000,
maxPendingOperations: 32,
});
try {
const info = await light.getDeviceInfo();
console.log(info.product, info.firmware.major, info.capabilities);
const result = await light.setPower(true);
console.log(result.outcome, result.observedState.power);
await light.setHsbk({ hue: 21845, saturation: 65535, brightness: 32768, kelvin: 3500 });
} catch (error) {
if (error instanceof LifxProtocolError) console.log(error.code, error.effectOutcome);
throw error;
} finally {
await light.close();
}getDeviceInfo() queries the vendor, product and full uint64 firmware build (bigint).
Its capabilities come from the documented official product registry
snapshot retrieved on 2026-10-06, including firmware-dependent kelvin ranges.
Unknown products remain available for identity queries. getLightState() and
setPower() require a known single-zone lighting product; setHsbk() additionally
requires color support and a kelvin value inside the actual firmware range.
The hue, saturation and brightness arguments are exact LAN uint16 values from
0 through 65535. There are no inferred percent, hue-angle or color conversions.
Matrix, chained, multizone and relay controls, effects, themes, HEV and infrared
controls are outside this API. White products support power and state reads,
and reject HSBK writes.
Write options accept durationMs from 0 through 60000, defaulting to zero.
All operations accept { signal: AbortSignal }; writes accept it alongside
durationMs. The deadline includes queue time, startup, capability queries,
acknowledgement and the separate state observation. maxPendingOperations
includes the active operation, defaults to 32, and may be set from 1 through 128.
Packets are spaced at least 50 milliseconds apart, replies must match the
configured UDP sender and the complete source/sequence/target/type correlation,
and a sequence wrap changes the source generation to reject old replies.
No message is retransmitted automatically. close() is terminal and idempotent,
and joins requests, timers, queued work and the socket.
LIFX acknowledges a set request before processing it. A successful write returns
{ outcome: 'accepted', observedState }; this is receipt acceptance with a
separately queried observation, which may precede completion or reflect a concurrent
writer. It does not promise physical completion. LifxProtocolError.effectOutcome
is not-sent, indeterminate, rejected (an exact StateUnhandled response), or
accepted when a later observation fails after an acknowledgement. An effect
without its acknowledgement is indeterminate and must not be retried automatically.
The implementation follows the official packet format, request and acknowledgement semantics, and state payload definitions. Opaque reserved reply bytes are ignored as in the official decoding example; all outgoing reserved bytes are zero. Verification uses loopback UDP fixtures; real device and firmware interoperability has not been verified.
Samsung TV Remote Protocol
SamsungTvProtocol provides bounded device-information reads and authenticated remote
control for Samsung TVs advertising the Tizen v2 remote channel. The configured UUID
must match /api/v2/ before pairing and before every key. Device snapshots contain
only observed device information, power state and the current remote capability
declarations; commands never change the snapshot optimistically.
import {
SamsungTvProtocol,
type ISamsungTvProtocolOptions,
} from '@ecobridge.xyz/devicemanager';
async function openTv(
trustedTvCa: string,
persistToken: ISamsungTvProtocolOptions['persistToken'],
): Promise<SamsungTvProtocol> {
const tv = new SamsungTvProtocol({
httpOrigin: 'http://192.168.1.55:8001',
websocketOrigin: 'wss://192.168.1.55:8002',
expectedDeviceId: '2ff68485-c4cb-48c7-a6ac-9c50e44d7084',
allowUnencryptedLocalDiscovery: true,
ca: trustedTvCa,
persistToken,
});
try {
await tv.start();
const result = await tv.sendKey('KEY_HOME');
// result.transport === 'sent'; result.effectOutcome === 'indeterminate'.
return tv;
} catch (error) {
await tv.close();
throw error;
}
}The caller must provide encrypted, durable, home-scoped pairing persistence. The
protocol awaits persistToken(token, signal) before enabling controls, and also
persists the confirmed token when an existing token is supplied. It owns no database,
file or cache and exposes no token getter. The callback must honor cancellation;
terminal close() cancels operations and joins any accepted persistence callback
and owned socket before resolving. It then clears its current token, channel and
persistence-callback references; immutable connection settings retain no token or
provider. Caller-owned configuration, provider closures and stored credentials remain
under caller control. Clearing references does not guarantee physical zeroization
of JavaScript strings; memory reclamation is controlled by the runtime. Start a fresh instance for an
explicit retry.
Pairing always uses WSS with certificate and hostname verification enabled. ca
adds an explicitly trusted CA; the certificate must identify the configured host.
There is no option to disable TLS checks. Unencrypted REST discovery is opt-in,
contains no token, authorization header or cookie, and only admits literal IPv4
private, link-local or loopback addresses, or IPv6 ULA and loopback addresses.
HTTPS REST and WSS must use the same host. Origins
cannot contain userinfo, paths, query parameters or fragments; redirects are rejected.
start({signal}), readDeviceInfo({signal}) and sendKey(key, {signal}) use one
operation deadline (10 seconds by default, maximum 120 seconds) and bounded HTTP
bodies/WebSocket frames (64 KiB by default, maximum 1 MiB). The remote key surface is
a fixed conservative set of single Click commands; directional keys additionally
require the current remote_fourDirections declaration. remote_available enables
the known protocol commands, rather than proving that a particular application will
act on each key. Concurrent key calls are rejected. No command is retried, repeated
or reconnected automatically.
The Samsung channel does not acknowledge a physical effect. A completed socket write
therefore returns {transport: 'sent', effectOutcome: 'indeterminate'}. Errors expose
a stable SamsungTvProtocolError.code and an effectOutcome of not-sent, rejected
or indeterminate; they exclude endpoint queries, tokens and remote error payloads.
Only startup pairing can be explicitly rejected. A lost effectful send remains
indeterminate. Power-on/Wake-on-LAN, absolute volume/mute assignment, app launch,
press/hold/release, legacy TCP/PIN protocols and Frame Art Mode are outside this API.
close() is terminal and always returns the same promise, including when a
persistence abort subscriber calls it again. It cancels operations and joins accepted
persistence callbacks and owned transports before clearing credentials. A persistence
failure that cancellation or timeout prevents start() from reporting is retained,
even if it settles before close; close rejects with an AggregateError containing
safe PERSISTENCE_FAILED errors. A failure already reported by start() is not
reported again by cleanup.
Cancellation reported through the operation's signal reason or an AbortError
DOMException is not a cleanup failure. Caller error messages and causes are excluded
because they may contain credentials.
After calling close(), retryCleanup() explicitly acknowledges those settled
failures. It waits for the close attempt and returns a shared acknowledgment promise;
it never repeats persistence, pairing or commands, and does not reopen the protocol.
The original close promise retains its result. Calling retryCleanup() before close
rejects with BUSY.
Protocol provenance: Samsung's Smart View sender documentation,
the upstream SamsungTVWS connection and remote command implementation,
and Home Assistant's SamsungTV bridge.
The implementation uses the existing ws transport; it does not copy those clients'
filesystem persistence, TLS bypasses or optimistic state behavior.
Home Assistant Integration
import { HomeAssistantProtocol, HomeAssistantDiscovery } from '@ecobridge.xyz/devicemanager';
// Connect to Home Assistant
const ha = new HomeAssistantProtocol({
host: 'homeassistant.local',
port: 8123,
token: 'your_long_lived_access_token',
});
await ha.connect();
// Get all entities
const entities = await ha.getStates();
// Control a light
await ha.callService(
'light',
'turn_on',
{ entity_id: 'light.living_room' },
{ brightness: 200 }
);
// Subscribe to state changes
await ha.subscribeToStateChanges();
ha.on('state:changed', (event) => {
console.log(`${event.entity_id}: ${event.new_state?.state ?? 'removed'}`);
});
// Auto-discover Home Assistant instances via mDNS
const discovery = new HomeAssistantDiscovery();
discovery.on('instance:found', (instance) => {
console.log(`Found HA at ${instance.host}:${instance.port}`);
});
await discovery.startMdnsDiscovery();Helper Utilities
import {
withRetry,
isValidIp,
cidrToIps,
getLocalSubnet,
} from '@ecobridge.xyz/devicemanager';
// Retry with exponential backoff
const result = await withRetry(
() => someFlakeyOperation(),
{ maxRetries: 3, baseDelay: 1000, multiplier: 2 }
);
// IP utilities
isValidIp('192.168.1.1'); // true
cidrToIps('192.168.1.0/30'); // ['192.168.1.1', '192.168.1.2']
getLocalSubnet(); // '192.168.1.0/24'🔍 Discovery Methods
The library supports multiple discovery mechanisms:
| Method | Protocol | Use Case |
|--------|----------|----------|
| discoverScanners() | eSCL, SANE | Find network scanners |
| discoverPrinters() | IPP | Find network printers |
| scanNetwork() | All | Comprehensive subnet scan |
| startDiscovery() | mDNS, SSDP, Bambu UDP 2021/1990 | Continuous auto-discovery |
mDNS Service Types
import { SERVICE_TYPES } from '@ecobridge.xyz/devicemanager';
// Keys: ESCL, ESCL_SECURE, SANE, IPP, IPPS, PDL,
// AIRPLAY, RAOP, SONOS, GOOGLECAST, SPOTIFY,
// OCTOPRINT, MOONRAKER, PRUSALINKmDNS discovery (MdnsDiscovery, HomeAssistantDiscovery and the mDNS part of startDiscovery()) runs in the device service. Every discovery of a process shares one service process, which starts with the first start() and stops with the last stop(). Without a service binary for the platform (such as on Windows), start() rejects with ERR_DEVICE_SERVICE_UNAVAILABLE; a service type that is not _<name>._tcp or _<name>._udp is refused with ERR_DISCOVERY_INVALID_PARAMS. Where the device service is unavailable, startDiscovery() runs SSDP and the Bambu listener without mDNS and passes the ERR_DEVICE_SERVICE_UNAVAILABLE error to DeviceManager's 'error' listeners, once per call and before it resolves. Any other startup failure of startDiscovery(), and an 'error' listener that throws, stops every transport again and rejects.
- Device ids are
<serviceType>:<address>:<port>. The address is the host's first IPv4 address, else its first IPv6 address (routable before link-local, then in numeric order); the device'saddressis the same one. - TXT entries without a value or with an empty value are left out; values are decoded as UTF-8 with invalid bytes replaced. Of a key that appears twice, the first entry counts.
- A changed TXT record or address list of a known device emits
device:updated; a device whose id changes is lost and found again. - Problems the service reports reach
'error'listeners of the discovery (and ofDeviceManager); without a listener they are not raised. If the service ends a discovery or exits, the discovery stops and emitsstopped. ECOBRIDGE_DEVICE_SERVICE_LOG(error,warn,info,debug,trace) sets the service's log level and, when set, writes its log records to stderr.
SSDP Service Types
import { SSDP_SERVICE_TYPES } from '@ecobridge.xyz/devicemanager';
// Root, DLNA media renderer/server, Sonos ZonePlayer,
// UPnP basic device and internet gateway service typesSsdpDiscovery uses native UDP sockets bound to every non-internal IPv4 interface. Searches are repeated every 30 seconds, and search(serviceType) can send an additional focused M-SEARCH while discovery is running.
Automatic discovery accepts only absolute, uncredentialed HTTP(S) LOCATION URLs whose literal IPv4 host equals the UDP sender's address. Admission happens before adding or updating a device and before HTTP I/O. Description fetches omit credentials and reject every redirect, including redirects on the same host. Invalid advertisements leave an existing device unchanged. DNS-name advertisements are excluded: supporting them safely requires verified resolution and pinning the actual HTTP connection to the advertised sender, rather than a separate DNS check followed by an unpinned fetch. SSDP advertisements remain unauthenticated discovery hints; callers must validate the selected device before trusting or controlling it.
import { SsdpDiscovery, SSDP_SERVICE_TYPES } from '@ecobridge.xyz/devicemanager';
const discovery = new SsdpDiscovery();
const startup = new AbortController();
await discovery.start([SSDP_SERVICE_TYPES.SONOS_ZONE_PLAYER], {
signal: startup.signal,
timeoutMs: 10000,
});
// Running discovery belongs to this instance until stop() completes.
await discovery.stop();start(serviceTypes?, options?) accepts ISsdpStartOptions: an optional startup signal and a total timeoutMs budget, including lifecycle queue time. The default budget is 10 seconds; explicit values must be integers from 1 to 60000 ms. Caller cancellation rejects with the signal's reason; expiration rejects with TimeoutError. Failed startup rejects after owned cleanup settles. After successful startup the caller signal is detached, so stop() owns running discovery teardown.
start() and stop() are idempotent. Calling stop() immediately cancels every startup already queued, pending bind and send operations, and description fetches. It waits for owned socket closure and pending work to settle. Startup requested after that stop can begin normally. Individual search sends have a 10-second deadline. Description requests retain a five-second deadline and accept at most 1 MiB, checked against advertised length and actual streamed bytes; unreachable or oversized descriptions leave the SSDP device without a description.
If socket closure fails, teardown attempts every socket and rejects with an AggregateError. The instance retains ownership of unclosed sockets and rejects another startup until an explicit stop() completes their closure. If startup and its cleanup both fail, the startup rejection includes both errors and identifies the startup error as its cause.
Runtime transport failures or throwing device:found/device:updated subscribers stop discovery and notify an attached error listener. The readonly lastError getter retains the latest runtime failure and resets on fresh startup. If an error listener also throws, lastError retains both failures in an AggregateError; owned cleanup still completes. Exceptions from started and stopped subscribers reject the corresponding lifecycle call after resource cleanup.
🎯 Feature Types
type TFeatureType =
| 'scan' // Document scanning
| 'print' // Document printing
| 'print3d' // 3D printing (Bambu Lab, Moonraker, OctoPrint, PrusaLink)
| 'fax' // Fax send/receive
| 'copy' // Copy (scan + print)
| 'playback' // Media playback
| 'volume' // Volume control
| 'power' // Power/UPS status
| 'snmp' // SNMP queries
| 'dlna-render'// DLNA renderer
| 'dlna-serve' // DLNA server
| 'light' // Smart lights
| 'climate' // HVAC/thermostats
| 'sensor' // Sensors
| 'camera' // Cameras
| 'cover' // Blinds, garage doors
| 'switch' // Smart switches
| 'lock' // Smart locks
| 'fan' // Fans
;🔧 Advanced Usage
Custom Device Creation
Use the factory functions for creating devices with specific features:
import { createScanner, createPrinter, createSpeaker } from '@ecobridge.xyz/devicemanager';
// Create a scanner device manually
const scanner = createScanner({
id: 'my-scanner',
name: 'Office Scanner',
address: '192.168.1.50',
port: 80,
protocol: 'escl',
txtRecords: {},
});
// Create a printer device
const printer = createPrinter({
id: 'my-printer',
name: 'Office Printer',
address: '192.168.1.51',
port: 631,
txtRecords: { rp: '/ipp/print' },
});
// Create a Sonos speaker with live UPnP playback and volume control attached
const speaker = createSpeaker({
id: 'living-room-sonos',
name: 'Living Room',
address: '192.168.1.52',
port: 1400,
protocol: 'sonos',
});Smart Home Factory Functions
The smart-home factories require a protocolClient that implements the corresponding feature interface, such as ILightProtocolClient for createSmartLight(). HomeAssistantProtocol exposes Home Assistant-specific service methods and entity state shapes, so it cannot be passed directly as that client; use a protocol adapter that implements the required interface.
Event Handling
DeviceManager, UniversalDevice, every Feature, and host-side providers
remain Node EventEmitter instances and additionally expose events$. Each
observable item contains the event name, its args, and emittedAt.
const manager = new DeviceManager();
const subscription = manager.events$.subscribe((event) => {
console.log(event.name, event.args, event.emittedAt);
});
// Discovery events
manager.on('device:found', ({ device, featureType }) => {
console.log(`Found ${device.name} with ${featureType} capability`);
});
manager.on('device:lost', (address) => {
console.log(`Device at ${address} went offline`);
});
// Network scan progress
manager.on('network:progress', (progress) => {
console.log(`Scanning: ${progress.percentage}% - Found ${progress.devicesFound} devices`);
});
// Device events
const device = manager.selectDevice({ address: '192.168.1.100' });
device.on('status:changed', ({ oldStatus, newStatus }) => {
console.log(`Status: ${oldStatus} → ${newStatus}`);
});
device.on('feature:connected', (featureType) => {
console.log(`Feature ${featureType} connected`);
});
subscription.unsubscribe();Error Handling
The library uses a fail-fast approach with clear error messages:
try {
// Throws if no device matches
const device = manager.selectDevice({ address: '192.168.1.999' });
} catch (err) {
// "No device found matching: {\"address\":\"192.168.1.999\"}"
}
try {
// Throws if device doesn't have the feature
const printFeature = device.selectFeature<PrintFeature>('print');
} catch (err) {
// "Device 'Brother Scanner' does not have feature 'print'"
}
// Safe alternatives that don't throw
const devices = manager.getDevices({ address: '192.168.1.999' }); // []
const maybePrint = device.getFeature<PrintFeature>('print'); // undefined📋 Requirements
- Node.js 18+ (native
fetchsupport required) - TypeScript 5.0+ (recommended)
- Network access to target devices
🙏 Credits
Built with ❤️ using:
- mdns-sd - mDNS discovery in the device service
- Node.js networking and fetch APIs - SSDP, IPP, eSCL, UPnP, and active network discovery
- net-snmp - SNMP protocol
- ws - Home Assistant, Moonraker and OctoPrint WebSocket transport
- MQTT.js - Bambu Lab printer status and commands
- basic-ftp - Bambu Lab implicit FTPS uploads
License and Legal Information
This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the license.md file.
Please note: The MIT License does not grant permission to use the trade names, trademarks, service marks, or product n
