🚀 Big News: Socket Acquires Coana to Bring Reachability Analysis to Every Appsec Team.Learn more
Socket
DemoInstallSign in
Socket

@node-wot/binding-mqtt

Package Overview
Dependencies
Maintainers
0
Versions
41
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@node-wot/binding-mqtt - npm Package Compare versions

Comparing version

to
0.9.0

0

dist/mqtt-broker-server.d.ts

@@ -0,0 +0,0 @@ import { MqttBrokerServerConfig } from "./mqtt";

295

dist/mqtt-broker-server.js

@@ -18,18 +18,19 @@ "use strict";

});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });

@@ -47,4 +48,8 @@ const mqtt = __importStar(require("mqtt"));

class MqttBrokerServer {
static brokerIsInitialized(broker) {
if (broker === undefined) {
throw new Error(`Broker not initialized. You need to start the ${MqttBrokerServer.name} before you can expose things.`);
}
}
constructor(config) {
var _a;
this.scheme = "mqtt";

@@ -61,4 +66,4 @@ this.ACTION_SEGMENT_LENGTH = 3;

this.things = new Map();
this.config = config !== null && config !== void 0 ? config : this.defaults;
this.config.uri = (_a = this.config.uri) !== null && _a !== void 0 ? _a : this.defaults.uri;
this.config = config ?? this.defaults;
this.config.uri = this.config.uri ?? this.defaults.uri;
if (config.uri.indexOf("://") === -1) {

@@ -69,43 +74,35 @@ config.uri = this.scheme + "://" + config.uri;

}
static brokerIsInitialized(broker) {
if (broker === undefined) {
throw new Error(`Broker not initialized. You need to start the ${MqttBrokerServer.name} before you can expose things.`);
async expose(thing) {
if (this.broker === undefined) {
return;
}
}
expose(thing) {
return __awaiter(this, void 0, void 0, function* () {
if (this.broker === undefined) {
return;
let name = thing.title;
if (this.things.has(name)) {
const suffix = name.match(/.+_([0-9]+)$/);
if (suffix !== null) {
name = name.slice(0, -suffix[1].length) + (1 + parseInt(suffix[1]));
}
let name = thing.title;
if (this.things.has(name)) {
const suffix = name.match(/.+_([0-9]+)$/);
if (suffix !== null) {
name = name.slice(0, -suffix[1].length) + (1 + parseInt(suffix[1]));
}
else {
name = name + "_2";
}
else {
name = name + "_2";
}
debug(`MqttBrokerServer at ${this.brokerURI} exposes '${thing.title}' as unique '${name}/*'`);
this.things.set(name, thing);
for (const propertyName of Object.keys(thing.properties)) {
this.exposeProperty(name, propertyName, thing);
}
for (const actionName of Object.keys(thing.actions)) {
this.exposeAction(name, actionName, thing);
}
for (const eventName of Object.keys(thing.events)) {
this.exposeEvent(name, eventName, thing);
}
this.broker.on("message", this.handleMessage.bind(this));
this.broker.publish(name, JSON.stringify(thing.getThingDescription()), { retain: true });
});
}
debug(`MqttBrokerServer at ${this.brokerURI} exposes '${thing.title}' as unique '${name}/*'`);
this.things.set(name, thing);
for (const propertyName of Object.keys(thing.properties)) {
this.exposeProperty(name, propertyName, thing);
}
for (const actionName of Object.keys(thing.actions)) {
this.exposeAction(name, actionName, thing);
}
for (const eventName of Object.keys(thing.events)) {
this.exposeEvent(name, eventName, thing);
}
this.broker.on("message", this.handleMessage.bind(this));
this.broker.publish(name, JSON.stringify(thing.getThingDescription()), { retain: true });
}
exposeProperty(name, propertyName, thing) {
var _a, _b;
MqttBrokerServer.brokerIsInitialized(this.broker);
const topic = encodeURIComponent(name) + "/properties/" + encodeURIComponent(propertyName);
const property = thing.properties[propertyName];
const writeOnly = (_a = property.writeOnly) !== null && _a !== void 0 ? _a : false;
const writeOnly = property.writeOnly ?? false;
if (!writeOnly) {

@@ -117,5 +114,5 @@ const href = this.brokerURI + "/" + topic;

debug(`MqttBrokerServer at ${this.brokerURI} assigns '${href}' to property '${propertyName}'`);
const observeListener = (content) => __awaiter(this, void 0, void 0, function* () {
const observeListener = async (content) => {
debug(`MqttBrokerServer at ${this.brokerURI} publishing to Property topic '${propertyName}' `);
const buffer = yield content.toBuffer();
const buffer = await content.toBuffer();
if (this.broker === undefined) {

@@ -126,6 +123,6 @@ warn(`MqttBrokerServer at ${this.brokerURI} has no client to publish to. Probably it was closed.`);

this.broker.publish(topic, buffer);
});
};
thing.handleObserveProperty(propertyName, observeListener, { formIndex: property.forms.length - 1 });
}
const readOnly = (_b = property.readOnly) !== null && _b !== void 0 ? _b : false;
const readOnly = property.readOnly ?? false;
if (!readOnly) {

@@ -159,3 +156,3 @@ const href = this.brokerURI + "/" + topic + "/writeproperty";

debug(`MqttBrokerServer at ${this.brokerURI} assigns '${href}' to Event '${eventName}'`);
const eventListener = (content) => __awaiter(this, void 0, void 0, function* () {
const eventListener = async (content) => {
if (this.broker === undefined) {

@@ -171,5 +168,5 @@ warn(`MqttBrokerServer at ${this.brokerURI} has no client to publish to. Probably it was closed.`);

debug(`MqttBrokerServer at ${this.brokerURI} publishing to Event topic '${eventName}' `);
const buffer = yield content.toBuffer();
const buffer = await content.toBuffer();
this.broker.publish(topic, buffer, { retain: form["mqv:retain"], qos: (0, util_1.mapQoS)(form["mqv:qos"]) });
});
};
thing.handleSubscribeEvent(eventName, eventListener, { formIndex: event.forms.length - 1 });

@@ -219,8 +216,7 @@ }

handleAction(action, packet, payload, segments, thing) {
var _a, _b, _c;
const contentType = (_b = (_a = packet === null || packet === void 0 ? void 0 : packet.properties) === null || _a === void 0 ? void 0 : _a.contentType) !== null && _b !== void 0 ? _b : core_1.ContentSerdes.DEFAULT;
const contentType = packet?.properties?.contentType ?? core_1.ContentSerdes.DEFAULT;
const options = {
formIndex: core_1.ProtocolHelpers.findRequestMatchingFormIndex(action.forms, this.scheme, this.brokerURI, contentType),
};
const formContentType = (_c = action.forms[options.formIndex].contentType) !== null && _c !== void 0 ? _c : core_1.ContentSerdes.DEFAULT;
const formContentType = action.forms[options.formIndex].contentType ?? core_1.ContentSerdes.DEFAULT;
const inputContent = new core_1.Content(formContentType, stream_1.Readable.from(payload));

@@ -239,10 +235,9 @@ thing

handlePropertyWrite(property, packet, payload, segments, thing) {
var _a, _b, _c, _d;
const readOnly = (_a = property.readOnly) !== null && _a !== void 0 ? _a : false;
const readOnly = property.readOnly ?? false;
if (!readOnly) {
const contentType = (_c = (_b = packet === null || packet === void 0 ? void 0 : packet.properties) === null || _b === void 0 ? void 0 : _b.contentType) !== null && _c !== void 0 ? _c : core_1.ContentSerdes.DEFAULT;
const contentType = packet?.properties?.contentType ?? core_1.ContentSerdes.DEFAULT;
const options = {
formIndex: core_1.ProtocolHelpers.findRequestMatchingFormIndex(property.forms, this.scheme, this.brokerURI, contentType),
};
const formContentType = (_d = property.forms[options.formIndex].contentType) !== null && _d !== void 0 ? _d : core_1.ContentSerdes.DEFAULT;
const formContentType = property.forms[options.formIndex].contentType ?? core_1.ContentSerdes.DEFAULT;
const inputContent = new core_1.Content(formContentType, stream_1.Readable.from(payload));

@@ -260,72 +255,65 @@ try {

}
destroy(thingId) {
return __awaiter(this, void 0, void 0, function* () {
debug(`MqttBrokerServer on port ${this.getPort()} destroying thingId '${thingId}'`);
let removedThing;
for (const name of Array.from(this.things.keys())) {
const expThing = this.things.get(name);
if (expThing != null && expThing.id != null && expThing.id === thingId) {
this.things.delete(name);
removedThing = expThing;
}
async destroy(thingId) {
debug(`MqttBrokerServer on port ${this.getPort()} destroying thingId '${thingId}'`);
let removedThing;
for (const name of Array.from(this.things.keys())) {
const expThing = this.things.get(name);
if (expThing != null && expThing.id != null && expThing.id === thingId) {
this.things.delete(name);
removedThing = expThing;
}
if (removedThing != null) {
info(`MqttBrokerServer successfully destroyed '${removedThing.title}'`);
}
if (removedThing != null) {
info(`MqttBrokerServer successfully destroyed '${removedThing.title}'`);
}
else {
info(`MqttBrokerServer failed to destroy thing with thingId '${thingId}'`);
}
return removedThing !== undefined;
}
async start(servient) {
if (this.brokerURI === undefined) {
warn(`No broker defined for MQTT server binding - skipping`);
}
else {
const selfHost = this.config.selfHost ?? false;
if (selfHost) {
await this.startBroker();
}
else {
info(`MqttBrokerServer failed to destroy thing with thingId '${thingId}'`);
if (this.config.psw === undefined) {
debug(`MqttBrokerServer trying to connect to broker at ${this.brokerURI}`);
}
return removedThing !== undefined;
});
}
start(servient) {
var _a;
return __awaiter(this, void 0, void 0, function* () {
if (this.brokerURI === undefined) {
warn(`No broker defined for MQTT server binding - skipping`);
else if (this.config.clientId === undefined) {
debug(`MqttBrokerServer trying to connect to secured broker at ${this.brokerURI}`);
}
else if (this.config.protocolVersion === undefined) {
debug(`MqttBrokerServer trying to connect to secured broker at ${this.brokerURI} with client ID ${this.config.clientId}`);
}
else {
const selfHost = (_a = this.config.selfHost) !== null && _a !== void 0 ? _a : false;
if (selfHost) {
yield this.startBroker();
}
if (this.config.psw === undefined) {
debug(`MqttBrokerServer trying to connect to broker at ${this.brokerURI}`);
}
else if (this.config.clientId === undefined) {
debug(`MqttBrokerServer trying to connect to secured broker at ${this.brokerURI}`);
}
else if (this.config.protocolVersion === undefined) {
debug(`MqttBrokerServer trying to connect to secured broker at ${this.brokerURI} with client ID ${this.config.clientId}`);
}
else {
debug(`MqttBrokerServer trying to connect to secured broker at ${this.brokerURI} with client ID ${this.config.clientId}`);
}
try {
this.broker = yield mqtt.connectAsync(this.brokerURI, this.config);
info(`MqttBrokerServer connected to broker at ${this.brokerURI}`);
const parsed = new url.URL(this.brokerURI);
this.address = parsed.hostname;
const port = parseInt(parsed.port);
this.port = port > 0 ? port : 1883;
}
catch (err) {
error(`MqttBrokerServer could not connect to broker at ${this.brokerURI}`);
throw err;
}
debug(`MqttBrokerServer trying to connect to secured broker at ${this.brokerURI} with client ID ${this.config.clientId}`);
}
});
}
stop() {
return __awaiter(this, void 0, void 0, function* () {
if (this.broker !== undefined) {
this.broker.unsubscribe("*");
this.broker.end(true);
try {
this.broker = await mqtt.connectAsync(this.brokerURI, this.config);
info(`MqttBrokerServer connected to broker at ${this.brokerURI}`);
const parsed = new url.URL(this.brokerURI);
this.address = parsed.hostname;
const port = parseInt(parsed.port);
this.port = port > 0 ? port : 1883;
}
if (this.hostedBroker !== undefined) {
yield new Promise((resolve) => this.hostedServer.close(() => resolve()));
yield new Promise((resolve) => this.hostedBroker.close(() => resolve()));
catch (err) {
error(`MqttBrokerServer could not connect to broker at ${this.brokerURI}`);
throw err;
}
});
}
}
async stop() {
if (this.broker !== undefined) {
this.broker.unsubscribe("*");
this.broker.end(true);
}
if (this.hostedBroker !== undefined) {
await new Promise((resolve) => this.hostedServer.close(() => resolve()));
await new Promise((resolve) => this.hostedBroker.close(() => resolve()));
}
}
getPort() {

@@ -338,7 +326,6 @@ return this.port;

selfHostAuthentication(_client, username, password, done) {
var _a;
if (this.config.selfHostAuthentication && username !== undefined) {
for (let i = 0; i < this.config.selfHostAuthentication.length; i++) {
if (username === this.config.selfHostAuthentication[i].username &&
password.equals(Buffer.from((_a = this.config.selfHostAuthentication[i].password) !== null && _a !== void 0 ? _a : ""))) {
password.equals(Buffer.from(this.config.selfHostAuthentication[i].password ?? ""))) {
done(null, true);

@@ -353,28 +340,26 @@ return;

}
startBroker() {
return __awaiter(this, void 0, void 0, function* () {
return new Promise((resolve, reject) => {
this.hostedServer = (0, aedes_1.Server)({});
let server;
if (this.config.key) {
server = tls.createServer({ key: this.config.key, cert: this.config.cert }, this.hostedServer.handle);
}
else {
server = net.createServer(this.hostedServer.handle);
}
const parsed = new url.URL(this.brokerURI);
const port = parseInt(parsed.port);
this.port = port > 0 ? port : 1883;
this.hostedServer.authenticate = this.selfHostAuthentication.bind(this);
const errorListener = (err) => {
error(`error listening for ${this.brokerURI}, ${err}`);
reject(err);
};
server.once("error", errorListener);
debug(`MqttBrokerServer creating server for ${this.brokerURI}`);
this.hostedBroker = server.listen(port, parsed.hostname, () => {
debug(`MqttBrokerServer listening ${this.brokerURI}`);
server.removeListener("error", errorListener);
resolve();
});
async startBroker() {
return new Promise((resolve, reject) => {
this.hostedServer = (0, aedes_1.Server)({});
let server;
if (this.config.key) {
server = tls.createServer({ key: this.config.key, cert: this.config.cert }, this.hostedServer.handle);
}
else {
server = net.createServer(this.hostedServer.handle);
}
const parsed = new url.URL(this.brokerURI);
const port = parseInt(parsed.port);
this.port = port > 0 ? port : 1883;
this.hostedServer.authenticate = this.selfHostAuthentication.bind(this);
const errorListener = (err) => {
error(`error listening for ${this.brokerURI}, ${err}`);
reject(err);
};
server.once("error", errorListener);
debug(`MqttBrokerServer creating server for ${this.brokerURI}`);
this.hostedBroker = server.listen(port, parsed.hostname, () => {
debug(`MqttBrokerServer listening ${this.brokerURI}`);
server.removeListener("error", errorListener);
resolve();
});

@@ -381,0 +366,0 @@ });

@@ -0,0 +0,0 @@ import { ProtocolClientFactory, ProtocolClient } from "@node-wot/core";

@@ -0,0 +0,0 @@ "use strict";

@@ -0,0 +0,0 @@ import { ProtocolClient, Content, Form, SecurityScheme } from "@node-wot/core";

@@ -18,18 +18,19 @@ "use strict";

});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {

@@ -52,115 +53,96 @@ return (mod && mod.__esModule) ? mod : { "default": mod };

}
subscribeResource(form, next, error, complete) {
var _a, _b;
return __awaiter(this, void 0, void 0, function* () {
const contentType = (_a = form.contentType) !== null && _a !== void 0 ? _a : core_1.ContentSerdes.DEFAULT;
const requestUri = new url.URL(form.href);
const brokerUri = `${this.scheme}://` + requestUri.host;
const filter = (_b = requestUri.pathname.slice(1)) !== null && _b !== void 0 ? _b : form["mqv:filter"];
let pool = this.pools.get(brokerUri);
if (pool == null) {
pool = new mqtt_message_pool_1.default();
this.pools.set(brokerUri, pool);
}
yield pool.connect(brokerUri, this.config);
yield pool.subscribe(filter, (topic, message) => {
next(new core_1.Content(contentType, stream_1.Readable.from(message)));
}, (e) => {
if (error)
error(e);
});
return new Subscription_1.Subscription(() => { });
async subscribeResource(form, next, error, complete) {
const contentType = form.contentType ?? core_1.ContentSerdes.DEFAULT;
const requestUri = new url.URL(form.href);
const brokerUri = `${this.scheme}://` + requestUri.host;
const filter = requestUri.pathname.slice(1) ?? form["mqv:filter"];
let pool = this.pools.get(brokerUri);
if (pool == null) {
pool = new mqtt_message_pool_1.default();
this.pools.set(brokerUri, pool);
}
await pool.connect(brokerUri, this.config);
await pool.subscribe(filter, (topic, message) => {
next(new core_1.Content(contentType, stream_1.Readable.from(message)));
}, (e) => {
if (error)
error(e);
});
return new Subscription_1.Subscription(() => { });
}
readResource(form) {
var _a, _b;
return __awaiter(this, void 0, void 0, function* () {
const contentType = (_a = form.contentType) !== null && _a !== void 0 ? _a : core_1.ContentSerdes.DEFAULT;
const requestUri = new url.URL(form.href);
const brokerUri = `${this.scheme}://` + requestUri.host;
const filter = (_b = requestUri.pathname.slice(1)) !== null && _b !== void 0 ? _b : form["mqv:filter"];
let pool = this.pools.get(brokerUri);
if (pool == null) {
pool = new mqtt_message_pool_1.default();
this.pools.set(brokerUri, pool);
}
yield pool.connect(brokerUri, this.config);
const result = yield new Promise((resolve, reject) => {
pool.subscribe(filter, (topic, message) => {
resolve(new core_1.Content(contentType, stream_1.Readable.from(message)));
}, (e) => {
reject(e);
});
async readResource(form) {
const contentType = form.contentType ?? core_1.ContentSerdes.DEFAULT;
const requestUri = new url.URL(form.href);
const brokerUri = `${this.scheme}://` + requestUri.host;
const filter = requestUri.pathname.slice(1) ?? form["mqv:filter"];
let pool = this.pools.get(brokerUri);
if (pool == null) {
pool = new mqtt_message_pool_1.default();
this.pools.set(brokerUri, pool);
}
await pool.connect(brokerUri, this.config);
const result = await new Promise((resolve, reject) => {
pool.subscribe(filter, (topic, message) => {
resolve(new core_1.Content(contentType, stream_1.Readable.from(message)));
}, (e) => {
reject(e);
});
yield pool.unsubscribe(filter);
return result;
});
await pool.unsubscribe(filter);
return result;
}
writeResource(form, content) {
var _a;
return __awaiter(this, void 0, void 0, function* () {
const requestUri = new url.URL(form.href);
const brokerUri = `${this.scheme}://${requestUri.host}`;
const topic = (_a = requestUri.pathname.slice(1)) !== null && _a !== void 0 ? _a : form["mqv:topic"];
let pool = this.pools.get(brokerUri);
if (pool == null) {
pool = new mqtt_message_pool_1.default();
this.pools.set(brokerUri, pool);
}
yield pool.connect(brokerUri, this.config);
const buffer = content === undefined ? Buffer.from("") : yield content.toBuffer();
yield pool.publish(topic, buffer, {
retain: form["mqv:retain"],
qos: (0, util_1.mapQoS)(form["mqv:qos"]),
});
async writeResource(form, content) {
const requestUri = new url.URL(form.href);
const brokerUri = `${this.scheme}://${requestUri.host}`;
const topic = requestUri.pathname.slice(1) ?? form["mqv:topic"];
let pool = this.pools.get(brokerUri);
if (pool == null) {
pool = new mqtt_message_pool_1.default();
this.pools.set(brokerUri, pool);
}
await pool.connect(brokerUri, this.config);
const buffer = content === undefined ? Buffer.from("") : await content.toBuffer();
await pool.publish(topic, buffer, {
retain: form["mqv:retain"],
qos: (0, util_1.mapQoS)(form["mqv:qos"]),
});
}
invokeResource(form, content) {
return __awaiter(this, void 0, void 0, function* () {
const requestUri = new url.URL(form.href);
const topic = requestUri.pathname.slice(1);
const brokerUri = `${this.scheme}://${requestUri.host}`;
let pool = this.pools.get(brokerUri);
if (pool == null) {
pool = new mqtt_message_pool_1.default();
this.pools.set(brokerUri, pool);
}
yield pool.connect(brokerUri, this.config);
const buffer = content === undefined ? Buffer.from("") : yield content.toBuffer();
yield pool.publish(topic, buffer, {
retain: form["mqv:retain"],
qos: (0, util_1.mapQoS)(form["mqv:qos"]),
});
return new core_1.DefaultContent(stream_1.Readable.from([]));
async invokeResource(form, content) {
const requestUri = new url.URL(form.href);
const topic = requestUri.pathname.slice(1);
const brokerUri = `${this.scheme}://${requestUri.host}`;
let pool = this.pools.get(brokerUri);
if (pool == null) {
pool = new mqtt_message_pool_1.default();
this.pools.set(brokerUri, pool);
}
await pool.connect(brokerUri, this.config);
const buffer = content === undefined ? Buffer.from("") : await content.toBuffer();
await pool.publish(topic, buffer, {
retain: form["mqv:retain"],
qos: (0, util_1.mapQoS)(form["mqv:qos"]),
});
return new core_1.DefaultContent(stream_1.Readable.from([]));
}
unlinkResource(form) {
return __awaiter(this, void 0, void 0, function* () {
const requestUri = new url.URL(form.href);
const brokerUri = `${this.scheme}://` + requestUri.host;
const topic = requestUri.pathname.slice(1);
const pool = this.pools.get(brokerUri);
if (pool != null) {
yield pool.unsubscribe(topic);
debug(`MqttClient unsubscribed from topic '${topic}'`);
}
});
async unlinkResource(form) {
const requestUri = new url.URL(form.href);
const brokerUri = `${this.scheme}://` + requestUri.host;
const topic = requestUri.pathname.slice(1);
const pool = this.pools.get(brokerUri);
if (pool != null) {
await pool.unsubscribe(topic);
debug(`MqttClient unsubscribed from topic '${topic}'`);
}
}
requestThingDescription(uri) {
return __awaiter(this, void 0, void 0, function* () {
throw new Error("Method not implemented");
});
async requestThingDescription(uri) {
throw new Error("Method not implemented");
}
start() {
return __awaiter(this, void 0, void 0, function* () {
});
async start() {
}
stop() {
return __awaiter(this, void 0, void 0, function* () {
for (const pool of this.pools.values()) {
yield pool.end();
}
if (this.client)
return this.client.endAsync();
});
async stop() {
for (const pool of this.pools.values()) {
await pool.end();
}
if (this.client)
return this.client.endAsync();
}

@@ -167,0 +149,0 @@ setSecurity(metadata, credentials) {

@@ -1,2 +0,1 @@

/// <reference types="node" />
import { MqttClientConfig } from "./mqtt";

@@ -3,0 +2,0 @@ import * as mqtt from "mqtt";

@@ -18,18 +18,19 @@ "use strict";

});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });

@@ -44,71 +45,59 @@ const core_1 = require("@node-wot/core");

}
connect(brokerURI, config) {
return __awaiter(this, void 0, void 0, function* () {
if (this.client === undefined) {
this.client = yield mqtt.connectAsync(brokerURI, config);
this.client.on("message", (receivedTopic, payload) => {
var _a;
debug(`Received MQTT message from ${brokerURI} (topic: ${receivedTopic}, data length: ${payload.length})`);
(_a = this.subscribers.get(receivedTopic)) === null || _a === void 0 ? void 0 : _a(receivedTopic, payload);
async connect(brokerURI, config) {
if (this.client === undefined) {
this.client = await mqtt.connectAsync(brokerURI, config);
this.client.on("message", (receivedTopic, payload) => {
debug(`Received MQTT message from ${brokerURI} (topic: ${receivedTopic}, data length: ${payload.length})`);
this.subscribers.get(receivedTopic)?.(receivedTopic, payload);
});
this.client.on("error", (error) => {
warn(`MQTT client error: ${error.message}`);
this.errors.forEach((errorCallback) => {
errorCallback(error);
});
this.client.on("error", (error) => {
warn(`MQTT client error: ${error.message}`);
this.errors.forEach((errorCallback) => {
errorCallback(error);
});
});
}
});
}
subscribe(filter, callback, error) {
return __awaiter(this, void 0, void 0, function* () {
if (this.client == null) {
throw new Error("MQTT client is not connected");
}
const filters = Array.isArray(filter) ? filter : [filter];
filters.forEach((f) => {
if (this.subscribers.has(f)) {
warn(`Already subscribed to ${f}; we are not supporting multiple subscribers to the same topic`);
warn(`The subscription will be ignored`);
return;
}
this.subscribers.set(f, callback);
this.errors.set(f, error);
});
yield this.client.subscribeAsync(filters);
});
}
}
unsubscribe(filter) {
return __awaiter(this, void 0, void 0, function* () {
if (this.client == null) {
throw new Error("MQTT client is not connected");
async subscribe(filter, callback, error) {
if (this.client == null) {
throw new Error("MQTT client is not connected");
}
const filters = Array.isArray(filter) ? filter : [filter];
filters.forEach((f) => {
if (this.subscribers.has(f)) {
warn(`Already subscribed to ${f}; we are not supporting multiple subscribers to the same topic`);
warn(`The subscription will be ignored`);
return;
}
const filters = Array.isArray(filter) ? filter : [filter];
filters.forEach((f) => {
this.subscribers.delete(f);
this.errors.delete(f);
});
yield this.client.unsubscribeAsync(filters);
this.subscribers.set(f, callback);
this.errors.set(f, error);
});
await this.client.subscribeAsync(filters);
}
publish(topic, message, options) {
return __awaiter(this, void 0, void 0, function* () {
if (this.client == null) {
throw new Error("MQTT client is not connected");
}
debug(`Publishing MQTT message to ${topic} (data length: ${message.length})`);
yield this.client.publishAsync(topic, message, options);
async unsubscribe(filter) {
if (this.client == null) {
throw new Error("MQTT client is not connected");
}
const filters = Array.isArray(filter) ? filter : [filter];
filters.forEach((f) => {
this.subscribers.delete(f);
this.errors.delete(f);
});
await this.client.unsubscribeAsync(filters);
}
end() {
var _a;
return __awaiter(this, void 0, void 0, function* () {
for (const filter of this.subscribers.keys()) {
this.unsubscribe(filter);
}
return (_a = this.client) === null || _a === void 0 ? void 0 : _a.endAsync();
});
async publish(topic, message, options) {
if (this.client == null) {
throw new Error("MQTT client is not connected");
}
debug(`Publishing MQTT message to ${topic} (data length: ${message.length})`);
await this.client.publishAsync(topic, message, options);
}
async end() {
for (const filter of this.subscribers.keys()) {
this.unsubscribe(filter);
}
return this.client?.endAsync();
}
}
exports.default = MQTTMessagePool;
//# sourceMappingURL=mqtt-message-pool.js.map

@@ -1,2 +0,1 @@

/// <reference types="node" />
import { Form } from "@node-wot/core";

@@ -11,3 +10,3 @@ export { default as MqttClient } from "./mqtt-client";

export * from "./mqtt-broker-server";
export declare type MqttQoS = "0" | "1" | "2";
export type MqttQoS = "0" | "1" | "2";
export declare class MqttForm extends Form {

@@ -14,0 +13,0 @@ "mqv:qos"?: MqttQoS;

@@ -0,0 +0,0 @@ "use strict";

@@ -0,0 +0,0 @@ import { ProtocolClientFactory, ProtocolClient } from "@node-wot/core";

@@ -0,0 +0,0 @@ "use strict";

import { MqttQoS } from "./mqtt";
import { IClientPublishOptions } from "mqtt";
export declare function mapQoS(qos: MqttQoS | undefined): Required<IClientPublishOptions>["qos"];
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.mapQoS = void 0;
exports.mapQoS = mapQoS;
const core_1 = require("@node-wot/core");

@@ -22,3 +22,2 @@ const { warn } = (0, core_1.createLoggers)("binding-mqtt", "mqtt-util");

}
exports.mapQoS = mapQoS;
//# sourceMappingURL=util.js.map
{
"name": "@node-wot/binding-mqtt",
"version": "0.8.16",
"version": "0.9.0",
"description": "MQTT binding for node-wot",

@@ -17,3 +17,3 @@ "author": "Eclipse Thingweb <thingweb-dev@eclipse.org> (https://thingweb.io/)",

"dependencies": {
"@node-wot/core": "0.8.16",
"@node-wot/core": "0.9.0",
"aedes": "^0.46.2",

@@ -20,0 +20,0 @@ "mqtt": "^5.3.2",

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet