Skip to content

Instantly share code, notes, and snippets.

@julianduque
Last active January 14, 2023 23:11
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save julianduque/9407471 to your computer and use it in GitHub Desktop.
Save julianduque/9407471 to your computer and use it in GitHub Desktop.
Primus + MQTT + Arduino == Internet of Things!
<input id="client" type="text" />
<input id="message" type="text" />
<button id="send">Send</button>
<script src="/primus/primus.js"></script>
<script type="text/javascript">
var primus = Primus.connect();
var client = document.getElementById('client');
var message = document.getElementById('message');
var send = document.getElementById('send');
send.onclick = function (e) {
e.preventDefault();
primus.write({ client: client.value, message: message.value });
}
</script>
var Primus = require('primus'),
http = require('http'),
mqtt = require('mqtt'),
util = require('util'),
url = require('url'),
fs = require('fs'),
qs = require('querystring'),
mq;
//
// Create http Server
//
var httpServer = http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/html' });
fs.createReadStream('index.html').pipe(res);
});
//
// Create WebSockets Server
//
var primus = new Primus(httpServer);
primus.on('connection', function (spark) {
spark.on('data', function (data) {
var client = mq && mq.clients[data.client];
if (client) {
client.publish({ topic: 'messages', payload: data.message });
}
});
});
//
// Create mqtt Server
//
var mqttServer = mqtt.createServer(function (client) {
mq = this;
if (!mq.clients) mq.clients = {};
client.on('connect', function (packet) {
mq.clients[packet.clientId] = client;
client.id = packet.clientId;
client.subscriptions = [];
console.log("Connected: " + client.id);
client.connack({ returnCode: 0 });
});
client.on("publish", function (packet) {
console.log(packet);
});
client.on("subscribe", function (packet) {
var granted = [];
for (var i = 0; i < packet.subscriptions.length; i++) {
var qos = packet.subscriptions[i].qos,
topic = packet.subscriptions[i].topic;
granted.push(qos);
client.subscriptions.push(topic);
}
client.suback({ granted: granted, messageId: packet.messageId });
});
client.on('pingreq', function (packet) {
client.pingresp();
});
client.on('disconnect', function (packet) {
client.stream.end();
});
client.on('close', function (packer) {
delete mq.clients[client.id];
});
client.on('error', function (err) {
client.stream.end();
console.log(err);
});
});
//
// Start Servers
//
mqttServer.listen(1883);
httpServer.listen(8080);
console.log("MQTT and HTTP Server listening");
#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>
#include <LiquidCrystal.h>
//
// Network Configuration
//
byte mac[] = { 0x90, 0xA2, 0xDA, 0x0E, 0x98, 0x91 };
byte server[] = { 192, 168, 1, 3 };
byte ip[] = { 192, 168, 1, 34 };
//
// Callback function header
//
void callback(char* topic, byte* payload, unsigned int length);
//
// toString function header
//
String toString(byte* payload, unsigned int length);
//
// Ethernet and MQTT Clients
//
EthernetClient ethClient;
PubSubClient client(server, 1883, callback, ethClient);
//
// LCD Shield
//
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);
void setup() {
//
// LCD Setup
//
lcd.begin(16, 2);
lcd.setCursor(0, 0);
lcd.print("MQTT Client");
//
// MQTT Client Setup
//
Ethernet.begin(mac, ip);
if (client.connect("ardx01")) {
client.subscribe("messages");
}
}
void loop() {
client.loop();
}
//
// MQTT Callback function
//
void callback(char* topic, byte* payload, unsigned int length) {
if (strcmp(topic, "messages") == 0) {
String msg = toString(payload, length);
//
// Print received message on LCD
//
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Received:");
lcd.setCursor(0, 1);
lcd.print(msg);
}
}
//
// toString function
//
String toString(byte* payload, unsigned int length) {
int i = 0;
char buff[length + 1];
for (i = 0; i < length; i++) {
buff[i] = payload[i];
}
buff[i] = '\0';
String msg = String(buff);
return msg;
}
{
"name": "iot",
"version": "0.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"author": "Julian Duque <julianduquej@gmail.com>",
"license": "MIT",
"dependencies": {
"mqtt": "^0.3.7",
"primus": "^2.0.3",
"ws": "^0.4.31"
}
}
@EdwardAHN
Copy link

Hi, Nice to meet you.
My name is Edward, at WIZnet in Korea.
We have been searching some application references in which WIZnet solution is applied, and found your project “MQTT“ using Ethernet Shield. In the Ethernet Shield WZnet’s W5100 chip is embedded. Your development looks very cool & smart.
Recently we opened WIZnet Museum (http://wiznetmuseum.com) site. This is a academic-purposed collection of open projects, tutorials, articles and etc from our global customers.
If you are O.K. we would like to introduce your projects in here. Hopefully, you will allow this.

Also, if you are interested, we would like to send the Ethernet shield of our latest chip version, W5500 or WiFi Shield.
(This is free sample, and shipment fee is ours, but if some tax exists related with this sample, then you should pay import tax by yourself. Some countries ask tax!)
You may be able to establish another project with them.
Hopefully, keep contacting us for the friendship.

Thank you very much

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment