Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
var mqtt = require('mqtt');
// Don't forget to update accessToken constant with your device access token
const thingsboardHost = "demo.thingsboard.io";
const ACCESS_TOKEN = "jSuvzrURCbw7q4LGtygc";
const minDirection = 0, maxDirection = 360;
// Initialization of mqtt client using Thingsboard host and device access token
console.log('Connecting to: %s using access token: %s', thingsboardHost, ACCESS_TOKEN);
var client = mqtt.connect('mqtt://'+ thingsboardHost, { username: ACCESS_TOKEN });
var value = 350;
var spinFlag = {method: "spinRight", params: 0};
//RPC message handling sent to the client
client.on('message', function (topic, message) {
console.log('request.topic: ' + topic);
console.log('request.body: ' + message.toString());
var tmp = JSON.parse(message.toString());
if (tmp.method == "spinRight") {
spinFlag = tmp;
// Uploads telemetry data using 'v1/devices/me/telemetry' MQTT topic
client.publish('v1/devices/me/telemetry', JSON.stringify({spinFlag: "rotating right"}));
}
if (tmp.method == "spinLeft") {
spinFlag = tmp;
function getPubSub() {
const mqttHost = process.env.MQTT_HOST
if (mqttHost) {
console.log('Using MQTT PubSub')
const mqttOptions = {
host: mqttHost,
servername: mqttHost, // needed to work in OpenShift. Lookup SNI.
username: process.env.MQTT_USERNAME || '',
password: process.env.MQTT_PASSWORD || '' ,
port: process.env.MQTT_PORT || '1883',
protocol: process.env.MQTT_PROTOCOL || 'mqtt',
rejectUnauthorized: false
}
const client = mqtt.connect(mqttHost, mqttOptions)
console.log(`attempting to connect to messaging service ${mqttHost}`)
client.on('connect', () => {
console.log('connected to messaging service')
})
client.on('error', (error) => {
console.log('error with mqtt connection')
console.log(error)
})
return new MQTTPubSub({ client })
}
console.log('Using In Memory PubSub')
return new PubSub()
public subscribeResource(form: MqttForm, next: ((value: any) => void), error?: (error: any) => void, complete?: () => void): any {
// get MQTT-based metadata
let contentType = form.contentType;
let retain = form["mqtt:retain"]; // TODO: is this needed here?
let qos = form["mqtt:qos"]; // TODO: is this needed here?
let requestUri = url.parse(form['href']);
let topic = requestUri.pathname;
let brokerUri : String = "mqtt://"+requestUri.host;
if(this.client==undefined) {
this.client = mqtt.connect(brokerUri)
}
this.client.on('connect', () => this.client.subscribe(topic))
this.client.on('message', (receivedTopic : string, payload : string, packet: IPublishPacket) => {
console.log("Received MQTT message (topic, data): (" + receivedTopic + ", "+ payload + ")");
if (receivedTopic === topic) {
next({ contentType: contentType, body: Buffer.from(payload) });
}
})
this.client.on('error', (error :any) => {
if (this.client) {
this.client.end();
}
this.client == undefined;
// TODO: error handling
error(error);
return new Promise(function(resolve, reject) {
if (self.status !== "disconnected") {
reject("MQTT broker client should be disconnected before it connects");
return;
}
self.status = "connecting";
var timer = setTimeout(function() {
log.error("connect", "Timeout to connect to", self.mnode.id, self.config.url, self.mqtt_config);
reject("Timeout to connect to MQTT with url " + self.config.url);
}, 10000);
self.client = mqtt.connect(self.config.url, self.mqtt_config);
self.client.on("connect", function() { // this might be triggered upon REconnection
if (self.status !== "connected") {
log("connect", "connected", self.mnode.id, self.config.url, self.mqtt_config);
self.status = "connected";
clearTimeout(timer);
self.client.on("error", function(err) {
log.error("error event", err, "for", self.config.url, self.mqtt_config);
});
self.client.on("message", function(t, m) {
self.handle_message(m);
});
resolve(self);
}
});
});
};
function start () {
log.setLevel(config.logging)
log.info(pkg.name + ' ' + pkg.version + ' starting')
const mqttOptions = { will: {
topic: config.name + '/connected',
message: 0,
qos: 0
} }
client = mqtt.connect(config.mqtt, mqttOptions)
setupMqttLogging()
// Create root dir for uploads
fs.access(tempdir, fs.constants.R_OK, (err) => {
if (err) {
fs.mkdir(tempdir, (err2) => {
if (err2) { throw err2 }
setupFtp()
})
} else {
setupFtp()
}
})
process.on('SIGINT', function () {
server.close()
connectAsync (brokerURL, opts, allowRetries=true) {
const client = mqtt.connect(brokerURL, opts);
const asyncClient = new AsyncClient(client);
return new Promise((resolve, reject) => {
// Listeners added to client to trigger promise resolution
const promiseResolutionListeners = {
connect: (connack) => {
removePromiseResolutionListeners();
resolve(asyncClient); // Resolve on connect
},
end: () => {
removePromiseResolutionListeners();
resolve(asyncClient); // Resolve on end
},
error: (err) => {
removePromiseResolutionListeners();
client.end();
const mqtt = require('mqtt');
///journey////////////
const topic = '/hfp/v1/journey/ongoing/+/+/+/+/+/+/+/+/+/#';
const client = mqtt.connect('mqtts://mqtt.hsl.fi:8883');
client.on('connect', function () {
client.subscribe(topic);
console.log('Connected');
});
let count = 0;
client.on('message', function (topic, message) {
const vehicle_position = JSON.parse(message).VP;
//Skip vehicles with invalid location
if (!vehicle_position.lat || !vehicle_position.long) {
return;
}
connect(url) {
if (this._url == url) return;
if (this.mqttConnect) {
this.client.end(true);
this.mqttConnect = false;
}
this._url = url;
this.client = mqtt.connect(this._url);
this.client.on("connect", () => {
this._connect = true;
this.emit("connect", true);
for (let i in this._subscribed) {
this.client.subscribe(this._subscribed[i]);
}
});
this.client.on("disconnect", () => {
this._connect = false;
this.emit("connect", false);
});
this.client.on("message", (topic, data) => {
this.publishBrokerStatus(AppConstants.ONLINE);
}.bind(this));
this.client.on('close', function () {
this.publishBrokerStatus(AppConstants.OFFLINE);
}.bind(this));
this.client.on('offline', function () {
this.publishBrokerStatus(AppConstants.OFFLINE);
}.bind(this));
this.client.on('error', function (err) {
this.publishBrokerStatus(AppConstants.OFFLINE);
}.bind(this));
this.client.on('message', function (topic, message,packet) {
var topics = _.uniq(this._matcher.match(topic));
if(message!=null && topics!=null && topics.length>0) {
for(var i=0;i
_createClient() {
this._mqttClient = mqtt.connect(this.model.brokerUrl, this.model.genConnectPrarms());
}