I have a raspberry pi with a Mosquitto Broker running on it connected to a sensor module with MQTT Protocol inbuilt. If I use this code in terminal, I can subscribe and see my data coming back.
mosquitto_sub -h 169.254.118.199 -t Advantech/00D0C9FA9984/data
When using a websocket method in my HTML/Javascript I can't make a connection. I am not 100% sure what port I need to specify, I have seen most posts using port 1883 but this doesn't seem to work. In terminal there is no port required.
This is working when running in the Terminal, I want to perform the same task through my web application.
My mosquitto.conf looks like this:
# Place your local configuration in /etc/mosquitto/conf.d/
#
# A full description of the configuration file is at
# /usr/share/doc/mosquitto/examples/mosquitto.conf.example
pid_file /var/run/mosquitto.pid
persistence true
persistence_location /var/lib/mosquitto/
#log_dest file /var/log/mosquitto/mosquitto.log
log_dest topic
log_type error
log_type warning
log_type notice
log_type information
include_dir /etc/mosquitto/conf.d
The webpage i am connecting to us http://192.168.1.40:5000/
In the web browser console, I can see that the connection request is timing out.
<div class="wrapper">
<h1>mqtt-demo</h1>
<form id="connection-information-form">
<b>Hostname or IP Address:</b>
<input id="host" type="text" name="host" value="169.254.118.199">
<br>
<b>Port:</b>
<input id="port" type="text" name="port" value="1883"><br>
<b>Topic:</b>
<input id="topic" type="text" name="topic"
value="Advantech/00D0C9FA9984/data"><br><br>
<input type="button" onclick="startConnect()" value="Connect">
<input type="button" onclick="startDisconnect()"
value="Disconnect">
</form>
<div id="messages"></div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/paho-
mqtt/1.0.1/mqttws31.js" type="text/javascript">
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
// Called after form input is processed
function startConnect() {
// Generate a random client ID
clientID = "clientID-" + parseInt(Math.random() * 100);
// Fetch the hostname/IP address and port number from the form
host = document.getElementById("host").value;
port = document.getElementById("port").value;
// Print output for the user in the messages div
document.getElementById("messages").innerHTML += '<span>Connecting to:
' + host + ' on port: ' + port + '</span><br/>';
document.getElementById("messages").innerHTML += '<span>Using the
following client value: ' + clientID + '</span><br/>';
// Initialize new Paho client connection
client = new Paho.MQTT.Client(host, Number(port), clientID);
// Set callback handlers
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;
// Connect the client, if successful, call onConnect function
client.connect({
onSuccess: onConnect,
});
}
// Called when the client connects
function onConnect() {
// Fetch the MQTT topic from the form
topic = document.getElementById("topic").value;
// Print output for the user in the messages div
document.getElementById("messages").innerHTML += '<span>Subscribing to: '
+ topic + '</span><br/>';
// Subscribe to the requested topic
client.subscribe(topic);
}
// Called when the client loses its connection
function onConnectionLost(responseObject) {
document.getElementById("messages").innerHTML += '<span>ERROR:
Connection lost</span><br/>';
if (responseObject.errorCode !== 0) {
document.getElementById("messages").innerHTML += '<span>ERROR: ' +
+ responseObject.errorMessage + '</span><br/>';
}
}
// Called when a message arrives
function onMessageArrived(message) {
console.log("onMessageArrived: " + message.payloadString);
document.getElementById("messages").innerHTML += '<span>Topic: ' +
message.destinationName + ' | ' + message.payloadString + '</span>
<br/>';
}
// Called when the disconnection button is pressed
function startDisconnect() {
client.disconnect();
document.getElementById("messages").innerHTML +=
'<span>Disconnected</span><br/>';
}
</script>
</head>
<head>
<meta http-equiv="refresh" content="450">
</head>
</html>
I expect a successful connection and the MQTT payload data. I am fairly new to MQTT.
As I said in the comments by default mosquitto does not configure a MQTT over WebSockets listener by default.
The Paho MQTT JavaScript client can only connect to a broker via MQTT over WebSockets.
To add a MQTT over WebSockets you need to add the following to the mosquitto.conf file (or to a file in /etc/mosquitto/conf.d)
listener 8083
protocol websockets
You would then need to make sure the client is connecting to port 8083
Related
New to JavaScript and Node.js
I have a setup where I have a raspberry pi running Node.js. The raspberry pi is connected to some embedded device through a USB to UART connection with the USB plugged into the raspberry pi. I can send and receive data at this base level just fine. The pi is connected to a router and I access it through it's IP and a browser.
I want to host a simple webpage that has a title, some text, and a button. When I click the button I want my client machine to contact the node.js server and make the pi send a message(already have a message format I am required to use) over the serial port to the embedded device. I want to wait/or not(depends on suggestions) for data to be sent back and then use that data to repopulate the text on the webpage.
What I have is close to this but not complete.
I run a 'server' on node.js off the pi. It uses express and a static page. The static page has a client side JavaScript file that executes a AJAX request when the button is clicked. On the node.js side I have express able to see the AJAX request. I then construct and send my message over serial port to the embedded device using serialport. At this point, on the Node.js side I can send back a string of text/etc. that can be displayed by the webpage but don't know how to somehow wait or other wise receive the data and send it to the webpage for displaying.
Client .html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Request Sensor Data</title>
<style type="text/css" media="screen"></style>
</head>
<body>
<p>Sensor Data</p>
<p><TEXTAREA id="myTxtArea" NAME="sensorDataTxtBox" ROWS=3 COLS=30 ></TEXTAREA></br>
<button type="button" name="sensorButton" id="mySensorButton" onClick="getSensorData()" >Get Sensor Data</button></p>
<script src="clientCode.js"></script>
</body>
</html>
Client .js:
function getSensorData()
{
console.log('getSensorData() button pushed.');
var xhr = new XMLHttpRequest();
xhr.open('GET', 'sensorGET');
xhr.send(null);
xhr.onreadystatechange = function () {
var DONE = 4; // readyState 4 means the request is done.
var OK = 200; // status 200 is a successful return.
if (xhr.readyState === DONE)
{
if (xhr.status === OK)
{
//insert DOM grabs to set text in html textbox.
console.log(xhr.responseText); // 'This is the returned text.'
var textAreaDOM = document.getElementById('myTxtArea');
textAreaDOM.value = textAreaDOM.value + 'inserted sensor data here\n';
}
else
{
console.log('Error: ' + xhr.status); // An error occurred during the request.
}
}
};
}
node.js .js:
var express = require('express'),
app = express();
app.use('/', express.static(__dirname + '/'));
app.get('/sensorGET', function (req, res) {
var sensorData = getSensorData();
res.send('sensorData');
})
var serialport = require('serialport'),
portname = '/dev/ttyUSB0';
var myPort = new serialport(portname, {
baudRate: 115200,
dataBits: 8,
parity: 'none',
stopBits: 1,
flowControl: false,
parser: serialport.parsers.byteLength(1)
});
myPort.on('open', showPortOpen);
myPort.on('data', recSerialData);
myPort.on('close', showPortClosed);
myPort.on('error', showError);
myPort.on('disconnect', showDisconnect);
function showDisconnect() {
console.log('Someone disconnected');
}
function showPortOpen()
{
console.log('port open. Data rate: ' + myPort.options.baudRate);
}
function recSerialData(data)
{
parseMessage(data);//This function is not shown but parses a message that is sent on the wire
}
function showPortClosed()
{
console.log('port closed.');
}
function showError(error)
{
console.log('Serial port error: ' + error);
}
function getSensorData()
{
myPort.write(Assume correct message is sent here);
//Can return some set text here and it will be written to the webpage.
//example: return "Temp data was asked for...";
//is there a way to wait here for the next message that comes in?
}
Probably the simplest thing will actually be to use something like socket.io and just send the data to the browser with that after every parseMessage. Because for starters if you try to make http wait for all serial data it will likely timeout, and the way things work its just easier to send every time you get a new data event from the serial port.
I'm having trouble while developing chat-like feature to my socket server.
First let me give you a little bit of my code:
document.conn = new ab.Session('ws://127.0.0.1:8090',
function () {
console.log('AB:Connected!');
conn.subscribe('room_1', function (topic, data) {
console.log('New message published to room "' + topic + '" : ' + data.content + ' by:' );
console.log(data);
});
},
function () {
console.warn('WebSocket connection closed');
},
{'skipSubprotocolCheck': true}
);
Currently it's attached to document just to try it out, the error I'm getting is as follows:
"Session not open"
I'm a bit confused about this error and it's origin, should I somehow define the connection?
do you start your socket server through cmd.exe ?
you need to use this command to start the server:
php c://wamp64/www/yourproject/bin/push-server.php
I wrote a piece of code that allows me search for all tweets hash tagged hello.
var stream = T.stream('statuses/filter', { track: 'hello', stall_warnings: true });
var counter = 0;
if (stream) {
console.log('connected!');
};
stream.on('tweet', function (tweet) {
console.log('tweet: '+ tweet.text);
console.log('by:' + ' #' + tweet.user.screen_name);
console.log('date:'+ ' ' + tweet.created_at + ' | ' + counter);
counter++;
});
How do I go about redirecting this so that I can create a web page that looks like a Twitter stream data, or something of the sort? Maybe using AngularJS.
You will have to create a web server first, try express.
then you can use something like sockets.io to communicate from the server to your client web page.
then on the webpage you must handle the messages to display them (angular, or maybe just jQuery) - basically on tweet you will send a message from your server to the client web page through socket.io, then your dront end javascript will get the message, parse it and decide how to display it.
Have a look at Sails.js, it's basically express with sockets integrated and a few more things
edit
say you export your server in server.js,
var http = require('./server.js');
var io = require('socket.io')(http);
stream.on('tweet', function (tweet) {
io.sockets.emit("new tweet", {
text: tweet.text,
by: tweet.user.screen_name,
date: tweet.created_at,
counter: counter++;
});
});
require('socket.io')(http) starts the "socket manager" on your server (and also publishes the js client side code for it), so clients can connect to your server through sockets.
io.sockets.emit will send a message to all connected clients.
on your web page you must have something like this
<div id="tweets"></div>
<script src="/your/js/jquery.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
socket.on("new tweet", function(tweet) {
$('#tweets').append('tweet: ' + tweet.text + '<br>');
$('#tweets').append('by:' + ' #' + tweet.by + '<br>');
$('#tweets').append('date:'+ ' ' + tweet.date + ' | ' + tweet.counter + '<br>');
});
</script>
the library /socket.io/socket.io.js was published by that require('socket.io')(http) from earlier, so we can use it on our clients.
the call io() basically connects to the server, and returns a handle to that connection (socket), we use that to receive all messages from the server, and on each message you can write the contents to the page anyway you want.
With socket.io you can broadcast events from the server to the client, in this case you could do something like this :
stream.on('tweet', function (tweet) {
io.sockets.emit("new tweet", tweet);
counter++;
});
And you could receive that event on the client-side like this :
var socket = io();
socket.on("new tweet", function(tweet){
//Do something with the tweet
});
This is a very basic and generic example, for more information you can look at the official documentation here.
I'm using Ratchet WebSockets and Autobahn.js for two-way client-server communication. I've installed everything, opened the ports, it's been weeks (yes, literally weeks) and it still doesn't work. I think I've narrowed it down to Autobahn's subscribe method not working correctly.
What I'm using is a slight modification of the example code found here:
http://socketo.me/docs/push
Here is my client code:
<script>
window.define = function(factory) {
try{ delete window.define; } catch(e){ window.define = void 0; } // IE
window.when = factory();
};
window.define.amd = {};
</script>
<script src="/apps/scripts/when.js"></script>
<script src="http://autobahn.s3.amazonaws.com/js/autobahn.min.js"></script>
<script>
var conn = new ab.Session(
'ws://light-speed-games.com:8080' // The host (our Ratchet WebSocket server) to connect to
, function() { // Once the connection has been established
console.log('Connection established.');
conn.subscribe('kittensCategory', function(topic, data) {
// This is where you would add the new article to the DOM (beyond the scope of this tutorial)
console.log('New article published to category "' + topic + '" : ' + data.title);
});
}
, function() { // When the connection is closed
console.warn('WebSocket connection closed');
}
, { // Additional parameters, we're ignoring the WAMP sub-protocol for older browsers
'skipSubprotocolCheck': true
}
);
</script>
I believe the problem lies here:
function() { // Once the connection has been established
console.log('Connection established.');
conn.subscribe('kittensCategory', function(topic, data) {
// This is where you would add the new article to the DOM (beyond the scope of this tutorial)
console.log('New article published to category "' + topic + '" : ' + data.title);
});
}
The line console.log('Connection established.'); does its job - it logs its message in the console. However, the conn.subscribe method does nothing. It doesn't matter if I change kittensCategory to any other string, it still does nothing. But kittensCategory is the only thing that makes sense here (see Ratchet's example code through the link above).
Any ideas?
EDIT:
This is the output of ab.debug:
WAMP Connect autobahn.min.js:69
ws://light-speed-games.com:8080 autobahn.min.js:69
wamp autobahn.min.js:69
WS Receive autobahn.min.js:64
ws://light-speed-games.com:8080 [null] autobahn.min.js:64
1 autobahn.min.js:64
[0,"52cbe9d97fda2",1,"Ratchet\/0.3"] autobahn.min.js:64
WAMP Welcome autobahn.min.js:67
ws://light-speed-games.com:8080 [52cbe9d97fda2] autobahn.min.js:67
1 autobahn.min.js:67
Ratchet/0.3 autobahn.min.js:67
Connection established. client.php:15
WAMP Subscribe autobahn.min.js:74
ws://light-speed-games.com:8080 [52cbe9d97fda2] autobahn.min.js:74
kittensCategory autobahn.min.js:74
function (topic, data) {
// This is where you would add the new article to the DOM (beyond the scope of this tutorial)
console.log('New article published to category "' + topic + '" : ' + data.title);
} autobahn.min.js:74
WS Send autobahn.min.js:72
ws://light-speed-games.com:8080 [52cbe9d97fda2] autobahn.min.js:72
1 autobahn.min.js:72
[5,"kittensCategory"]
I created a simple application as an attempt to integrate node, express, socket.io, and jade. The user enters some string ("tool ID") in a text field and clicks a submit button. That text is simply converted to all uppercase and the result is appended to the results section on the page. The results should be automatically updated for other clients viewing the page.
It mostly works. However the problem is that right after the user clicks the submit button on the page to submit the tool ID, the node console and browser javascript console both show the client disconnecting and then reconnecting.
To the user it looks like the results are updated correctly for a fraction of a second. Then the results go blank for another fraction of a second. Then the results are redisplayed. Since I am showing the user's session ID with the results, I can see that the session ID changes during the short time while the results go blank.
Note that if a different client is simply viewing the page, but not otherwise interacting, the results are updated smoothly (no brief time of results going blank) and that client doesn't seem to be disconnecting at all.
I don't want the client to disconnect and reconnect when they click the submit button on the form. Can someone tell me why this is happening and how I should be doing it properly?
My app.js (server)
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
io = require('socket.io').listen(server); // without the var, this becomes available to other files like routes.
var path = require('path');
var routes = require('./routes/routes');
var process = require('./routes/process');
var _ = require("underscore");
// all environments
app.set('port', 3097);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
//app.use(express.logger('dev'));
app.use(express.bodyParser()); //Tells server to support JSON, urlencoded, and multipart requests
app.use(express.methodOverride());
app.use(express.cookieParser('i7iir5b76ir857bveklfgf'));
app.use(express.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
var toolIDs = [];
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
io.on("connection", function(socket) {
console.log("Client connected. Sending Update");
socket.on("toolsRequest", function() {
socket.emit('toolsReady', {toolIDs: toolIDs}); //This should go to the client that just connected.
});
socket.on("disconnect", function() {
console.log("Client Disconnected");
});
socket.on("toolsUpdate", function(data) {
processedToolID = process.process(data.toolID);
toolIDs.push({id: data.id, inputToolID: data.toolID, outputToolID: processedToolID});
io.sockets.emit("toolsUpdated", {toolIDs: toolIDs}); //This should go to all clients
console.log('Results Updated - notifying all clients');
});
});
// display main page
app.get('/', routes.home);
server.listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
My routes.js
/*
* GET home page.
*/
exports.home = function(req, res){
res.render('home', { title: 'Tool'});
console.log("Just called route.home");
};
My home.jade
doctype 5
html
head
title= title
link(rel='stylesheet', href='/bootstrap/css/bootstrap.min.css')
link(rel='stylesheet', href='/bootstrap/css/bootstrap-responsive.min.css')
script(src='/socket.io/socket.io.js')
script(src="http://code.jquery.com/jquery.min.js")
script(src='/js/index.js')
block content
#wrapper
h1
a(href='/') TOOL
#display
div.row-fluid
div.inlineBlock
form#toolForm
label Tool ID
input(type="text", placeholder="e.g. abc123")#toolID
span.help-block You may enter a string.
button(class="btn")#submit
| Submit
br
div.inlineBlock.topAligned
h2 Results
br
div#results
br
My index.js (client)
function init() {
/*
On client init, try to connect to the socket.IO server.
*/
var socket = io.connect('http://example.com:3097/');
//We'll save our session ID in a variable for later
var sessionID = '';
//Helper function to update the results
function updateResults(toolIDs) {
$('#results').html('');
for (var i = 0; i < toolIDs.length; i++) {
$('#results').append('<span id="' + toolIDs[i].id + '">' + '<b>Creator ID:</b> ' + toolIDs[i].id + ' <b>Your ID:</b> ' + sessionID + ' <b>Input Tool:</b> ' + toolIDs[i].inputToolID + ' <b>Output Tool:</b> ' + toolIDs[i].outputToolID + (toolIDs[i].id === sessionID ? '<b>(You)</b>' : '') + '<br /></span>');
}
}
/*
When the client successfully connects to the server, an
event "connect" is emitted.
*/
socket.on('connect', function () {
sessionID = socket.socket.sessionid;
// Note this appears in the browser Javascript console, not node console
console.log('You are connected as: ' + sessionID);
socket.emit('toolsRequest'); //Request the tools data so we can update results
});
socket.on('toolsReady', function(data) {
updateResults(data.toolIDs);
console.log('Results have been updated from socket.on.toolsReady');
});
socket.on('toolsUpdated', function (data) {
updateResults(data.toolIDs);
console.log('Results updated from socket.on.toolsUpdated');
});
/*
Log an error if unable to connect to server
*/
socket.on('error', function (reason) {
console.log('Unable to connect to server', reason);
});
function getCitations() {
var toolID = $('#toolID').val()
socket.emit('toolsUpdate', {id: sessionID, toolID: toolID});
}
$('#submit').on('click', getCitations);
}
$(document).on('ready', init);
Here's what I see in the node console when a client clicks the submit button:
debug - websocket writing 5:::{"name":"toolsUpdated","args":[{"toolIDs":[{"id":"5a1dfX2dmxcogYT_11e8","inputToolID":"a123123","outputToolID":"A123123"},{"id":"OIuqao6TsTeddQm111e-","inputToolID":"1abcdefg","outputToolID":"1ABCDEFG"},{"id":"Qr_YQ2ZhQHbDpBlk11e_","inputToolID":"abcdefg","outputToolID":"ABCDEFG"}]}]}
Results Updated - notifying all clients
Just called route.home
info - transport end (socket end)
debug - set close timeout for client Qr_YQ2ZhQHbDpBlk11e_
debug - cleared close timeout for client Qr_YQ2ZhQHbDpBlk11e_
debug - cleared heartbeat interval for client Qr_YQ2ZhQHbDpBlk11e_
Client Disconnected
debug - discarding transport
debug - served static content /socket.io.js
debug - client authorized
info - handshake authorized 2bPKGgmLdD4fp-vz11fA
debug - setting request GET /socket.io/1/websocket/2bPKGgmLdD4fp-vz11fA
debug - set heartbeat interval for client 2bPKGgmLdD4fp-vz11fA
debug - client authorized for
debug - websocket writing 1::
Client connected. Sending Update
debug - websocket writing 5:::{"name":"toolsReady","args":[{"toolIDs":[{"id":"5a1dfX2dmxcogYT_11e8","inputToolID":"a123123","outputToolID":"A123123"},{"id":"OIuqao6TsTeddQm111e-","inputToolID":"1abcdefg","outputToolID":"1ABCDEFG"},{"id":"Qr_YQ2ZhQHbDpBlk11e_","inputToolID":"abcdefg","outputToolID":"ABCDEFG"}]}]}
Thanks, I appreciate the help.
Your submit button is actually reloading the page, which is why the socket is disconnecting, and why you see the socket response for such a short time. Just prevent the default action of the submit button. Change this:
$('#submit').on('click', getCitations);
To something similar:
$('#submit').click(function(event) {
event.preventDefault();
getCitations();
});