-
• #2
You could try registering for the
connected
event before you call connect. It might help - it's definitely what gets done in the examples on http://www.espruino.com/MQTT -
• #3
Thank you, Gordon.
do you mean put it in order like this?function mqttRun(){ var server = 'my_broker'; var options = { keep_alive: 60, port: my_port, clean_session: my_port, username: "my_user", password: "my_pass", protocol_name: "MQTT", protocol_level: 4, }; var mqtt = require("MQTT").create(server); mqtt.on('connected', function() { mqtt.subscribe("test"); }); mqtt.connect(options); }
I tried now - same error
>mqttRun() Client connected Uncaught Error: Function "write" not found!
What I'm doing wrong?
UPD. I saw this subject - http://forum.espruino.com/conversations/293870
example in post #5 and mine shoud do the same, but they don't -
• #4
ok. this problem solved by setting options when 'create'
but i have next one. i can see messages in debug, but mqtt module give me error again
function mqttRun(){ var server = 'my_broker'; var options = { keep_alive: 60, port: my_port, clean_session: my_port, client_id: "my_id", username: "my_user", password: "my_pass", protocol_name: "MQTT", protocol_level: 4, }; var mqtt = require("MQTT").create(server, options); // changes here mqtt.on('connected', function() { mqtt.subscribe("/test"); }); mqtt.on('publish', function (pub) { // this place throw error console.log("topic: "+pub.topic); console.log("message: "+pub.message); }); mqtt.connect(); }
Uncaught Error: Field or method "topic" does not already exist, and can't create it on undefined
-
• #5
Ok, glad you got that sorted - do you know what exactly the issue was? Missing
client_id
? Are you using up to date firmware, as it should really have reported a different error.For your new error, could you just try removing
console.log("topic: "+pub.topic);
- it could be thatpub
doesn't have a field in it called topic? -
• #6
Actually can you try this instead:
mqtt.on('publish', function (pub) { console.log(JSON.stringify(pub)); });
It looks like 'publish' can return undefined if it doesn't understand the MQTT packet that it was sent, which would produce your error
-
• #7
Gordon, thank you, i'll definitely try with json. I already looked through module code and and notice, when it can be undefined, so run my code without pub.topic and pub.message. mqtt.on('publish', ...) can catch the event, thats good. But still need to read messages for my project and still look for solution. Will try use JSON.stringify(pub) today and tell about result.
And about first problem: it was solved when i set my options object as a parameter of 'create' function like this: mqtt.create (server, options);
setting client_id didn't help, but i tried :)
By the way, I still have issue in the connect (a.write dose not already exist, if i'm not mistaken), but this solution let mqtt run, so for now i just ignore the issue. -
• #8
Thanks for letting me know - it looks like the last updated to the documentation wasn't tested at all. Looking through it I've spotted loads of bugs in the example code now :(
I'll push an update soon.
-
• #9
Gordon and thank you for support! I really appreciate it.
Ok, about 'json-solution'. I've been testing it for few hours.
it's not working for the moment.
best results look like this:JSON TEST {"topic":"3865","message":"","dup":1,"qos":0,"retain":0}
topic was '/test', message contain a string, but not ':'
most part I've got undefined and thats it. But in debug i can see whole message and topic as it was sent.
As well I got one new error:Uncaught Error: Unknown Timeout at line 2 col 149 ...ACK)if(clearTimeout(b.ctimo),c=c.charCodeAt(3),0===c)b.conne...
it's not crash the script, but still.
About MQTT packet: all the time i having 'MQTT unsupported packet type: 6' and 'MQTT unsupported packet type: 7'.
It's the same when I send message either from espruino, websocket console or android client.
Maybe I can change type somehow? How it works? Need a research this.and as soon as i can see topic and message in debug, probably i can get it to some buffer as well? I tried AT module, but not succeed with it so far.
-
• #10
For the unsupported packet type, see http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Table_2.1_-
Looks a lot like 6 and 7 are for
assured delivery
- I guess that's some kind of QoS - when the MQTT library only supports QoS 0.To be honest QoS>0 isn't really so important over TCP/IP since TCP/IP will already be doing error correction and packet management for you.
I wonder whether you're connecting to an MQTT-SN server rather than normal MQTT, or something like that?
-
• #11
lI wonder whether you're connecting to an MQTT-SN server rather than normal MQTT, or something like that?
I'm not sure that understand you right way, do you ask which broker I use? If so, I try cloudmqtt.com and iot.eclipse.org - same result.
And today I have a new problem with my yesterday-somehow-worked code. Espruino can't publish messages now.Uncaught Error: Field or method "length" does not already exist, and can't create it on Number at line 1 col 88 ...lish",c),b.emit("message",c.topic,c.message);else if(d!==f.P... ^ in function called from system at line 1 col 24 a=g(a);var c=b.length+e.length,d="";do{var f=c&127,c=c>>7;0<... ^ in function "m" called from line 1 col 95 ...?l(a):l(a)+d;return m(c,a,b) ^ in function "q" called from line 1 col 42 this.client.write(q(a,b,e||this.C.DEF_QOS)) ^ in function "publish" called from line 45 col 36 mqtt.publish('/iskra', humidity); ^
Could it be relevant to last updates? didn't look to changes so far.
-
• #12
I just tested here on an Espruino Wifi board with your code - publish and subscribe seem to work ok for me. Seems like your issue is that
humidity
isn't a string?I just saw
'/iskra'
in the.publish
command - are you using this on an IskraJS board?If so, you should really be asking Amperka for help - or at least letting us know that you're not using an Espruino board. Amperka are using Espruino for free - I can't afford to spend hours of my time supporting their customers as well!
-
• #13
Oh. I'm really sorry for bothering you. I didn't know that it is working this way, thought that it's just a forum where people could ask questions.
I didn't met anybody here who used MQTT on js controller and not much people working with internet connection on js contoller. Usually it's just kids plays and thats it. I think, js controllers can do really great things and try to prove it.
I didn't tell about iskra just because don't think it could be important. So, please accept my I apologize. It certainly was not intentional. -
• #14
@Ickis There is this module also: https://github.com/olliephillips/tinyMQTT. You may experience the same issues, but worth a shot. Note the API is slightly different but it's on the README
-
• #15
Ollie, thank you, didn't see that one. Will definitely try it and share the result.
-
• #16
No problem, it's fine. I'm in a difficult situation - I want the forum to be to help other people out, but because I put a lot of time (~3 hours a day) into trying to help everyone on the forum and email, it makes life difficult if I end up spending that time helping out another company's customers!
@Ickis I believe if you try again, after i posted the last comment I think I fixed the issues you were having with the MQTT module?
-
• #17
@Gordon Sure, I can understand it. Actually, I was really surprised, when get answer from developer of module and such attention for my problem. It's of course takes time from you and your help is really appreciated. Sorry again for this misunderstanding.
I didn't try MQTT module since friday's early morning. But when I do, let know what will get. I need to test Ollie suggestion as well. -
• #18
Just as a follow up I am testing with a pico wifi, eMQ as the broker, I see random errors with this code on the device:
var server = "ubuntu.home"; // the ip of your MQTT broker var options = { // all optional - the defaults are below client_id : getSerial(), // the client ID sent to MQTT - it's a good idea to define your own static one based on `getSerial()` keep_alive: 60, // keep alive time in seconds port: 1883, // port number clean_session: true, username: "stephen", // default is undefined password: "*****", // default is undefined protocol_name: "MQTT", // or MQIsdp, etc.. protocol_level: 4, // protocol level }; var mqtt = require("MQTT").create(server, options /*optional*/); mqtt.on('connected', function() { mqtt.subscribe("test/espruino"); }); mqtt.on('publish', function (pub) { console.log(JSON.stringify(pub)); console.log("topic: "+pub.topic); console.log("message: "+pub.message); }); var WIFI_NAME = "****"; var WIFI_OPTIONS = { password : "****" }; var wifi = require("EspruinoWiFi"); function getPage() { require("http").get("http://www.pur3.co.uk/hello.txt", function(res) { console.log("Response: ",res); res.on('data', function(d) { console.log("--->"+d); mqtt.publish("test/espruino", d); }); }); } function makeid() { var text = ""; var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; for( var i=0; i < 5; i++ ) text += possible.charAt(Math.floor(Math.random() * possible.length)); console.log('makeid: '+text); return text; } function postIt() { var msg = "MSG: " + makeid(); mqtt.publish("test/espruino", msg); } wifi.connect(WIFI_NAME, WIFI_OPTIONS, function(err) { if (err) { console.log("Connection error: "+err); return; } console.log("Connected!"); wifi.getIP(function (err, res) { if (!err) { console.log(res.ip); mqtt.connect(); } else { console.log(err); } }); getPage(); ts = setInterval(function() {postIt();}, 20000); });
It seems to randomly add \xD0\x00 to the message.
Console.log
1v91 Copyright 2016 G.Williams > =undefined Connected! 192.168.1.226 Client connected Response: httpCRs { "headers": { "Date": "Tue, 04 Apr 2017 19:19:23 GMT", "Server": "Apache/2.4.18 (Ubuntu)", "Last-Modified": "Fri, 15 Nov 2013 15:42:26 GMT", "ETag": "\"d-4eb390b887c80\"", "Accept-Ranges": "bytes", "Content-Length": "13", "Connection": "close", "Content-Type": "text/plain" }, "httpVersion": "1.1", "statusCode": "200", "statusMessage": "OK" } --->Hello World! MQTT connection accepted {"topic":"test/espruino","message":"from server","dup":0,"qos":0,"retain":1} topic: test/espruino message: from server makeid: gRQRa undefined Uncaught Error: Field or method "topic" does not already exist, and can't create it on undefined at line 1 col 88 ...lish",c),a.emit("message",c.topic,c.message);else if(d!==f.P... ^ in function called from system at line 2 col 28 console.log("topic: "+pub.topic); ^ in function called from system MQTT unsupported packet type: 0 [MQTT]0,13,116,101,115,116,47,101,115,112,114,117,105,110,111,77,83,71,58,32,103,82,81,82,97 makeid: sJZwi {"topic":"test/espruino","message":"MSG: sJZwi\xD0\x00","dup":0,"qos":0,"retain":0} topic: test/espruino message: MSG: sJZwiÐ makeid: kL0LJ {"topic":"test","message":"","dup":0,"qos":0,"retain":0} topic: test message: Uncaught Error: Unknown Timeout at line 2 col 149 ...ACK)if(clearTimeout(a.ctimo),c=c.charCodeAt(3),0===c)a.conne... ^ in function called from system makeid: GJTbH {"topic":"test/espruino","message":"MSG: GJTbH\xD0\x00","dup":0,"qos":0,"retain":0} topic: test/espruino message: MSG: GJTbHÐ makeid: pUTU1 undefined Uncaught Error: Field or method "topic" does not already exist, and can't create it on undefined at line 1 col 88 ...lish",c),a.emit("message",c.topic,c.message);else if(d!==f.P... ^ in function called from system at line 2 col 28 console.log("topic: "+pub.topic); ^ in function called from system MQTT unsupported packet type: 6 [MQTT]101,115,116,47,101,115,112,114,117,105,110,111,77,83,71,58,32,112,85,84,85,49 makeid: 6QAbL {"topic":"test/espruino","message":"MSG: 6QAbL\xD0\x00","dup":0,"qos":0,"retain":0} topic: test/espruino message: MSG: 6QAbLÐ makeid: demXD {"topic":"tes","message":"","dup":0,"qos":0,"retain":0} topic: tes message: MQTT unsupported packet type: 7 [MQTT]116,47,101,115,112,114,117,105,110,111,77,83,71,58,32,100,101,109,88,68 >
-
• #19
Update. testing with QoS
mqtt.publish("test/espruino", msg, 1);
1v91 Copyright 2016 G.Williams > =undefined Connected! 192.168.1.226 Client connected Response: httpCRs { "headers": { "Date": "Tue, 04 Apr 2017 19:34:40 GMT", "Server": "Apache/2.4.18 (Ubuntu)", "Last-Modified": "Fri, 15 Nov 2013 15:42:26 GMT", "ETag": "\"d-4eb390b887c80\"", "Accept-Ranges": "bytes", "Content-Length": "13", "Connection": "close", "Content-Type": "text/plain" }, "httpVersion": "1.1", "statusCode": "200", "statusMessage": "OK" } --->Hello World! MQTT connection accepted makeid: swv0V MQTT unsupported packet type: 5 [MQTT]86 makeid: 1HPH2 makeid: 8h85j MQTT unsupported packet type: 5 [MQTT]83,71,58,32,56,104,56,53,106 makeid: wCyVx makeid: l2Chh makeid: gbk2L makeid: 5HdG8 makeid: wWLvZ makeid: 6PHch MQTT unsupported packet type: 5 [MQTT]80,72,99,104 makeid: 1fuue makeid: sctqL MQTT unsupported packet type: 6 [MQTT]99,116,113,76 makeid: Rkpqp makeid: FqKuv MQTT unsupported packet type: 7 [MQTT]117,118 makeid: G6wsU makeid: j3g6z MQTT unsupported packet type: 6 [MQTT]106,51,103,54,122 makeid: 5RuIk makeid: hJLhd >
eMQ Console subscribed test/# QoS 1
2017-04-04 20:36:33 --(Q1, R1, D0, Topic=test/espruino, Payload=from server) 2017-04-04 20:36:40 --(Q1, R0, D0, Topic=test/espruino, Payload=MSG: gbk2L) 2017-04-04 20:37:00 --(Q1, R0, D0, Topic=test/espruino, Payload=MSG: 5HdG8) 2017-04-04 20:37:20 --(Q1, R0, D0, Topic=test/espruino, Payload=MSG: wWLvZ) 2017-04-04 20:37:40 --(Q1, R0, D0, Topic=test/espruino, Payload=MSG: 6PHch) 2017-04-04 20:38:00 --(Q1, R0, D0, Topic=test/espruino, Payload=MSG: 1fuue) 2017-04-04 20:38:20 --(Q1, R0, D0, Topic=test/espruino, Payload=MSG: sctqL) 2017-04-04 20:38:40 --(Q1, R0, D0, Topic=test/espruino, Payload=MSG: Rkpqp) 2017-04-04 20:39:00 --(Q1, R0, D0, Topic=test/espruino, Payload=MSG: FqKuv) 2017-04-04 20:39:20 --(Q1, R0, D0, Topic=test/espruino, Payload=MSG: G6wsU) 2017-04-04 20:39:40 --(Q1, R0, D0, Topic=test/espruino, Payload=MSG: j3g6z) 2017-04-04 20:40:00 --(Q1, R0, D0, Topic=test/espruino, Payload=MSG: 5RuIk) 2017-04-04 20:40:20 --(Q1, R0, D0, Topic=test/espruino, Payload=MSG: hJLhd) 2017-04-04 20:40:40 --(Q1, R0, D0, Topic=test/espruino, Payload=MSG: sF75w) 2017-04-04 20:41:00 --(Q1, R0, D0, Topic=test/espruino, Payload=MSG: x87O6)
mqtt.publish("test/espruino", msg, 2);
1v91 Copyright 2016 G.Williams > =undefined Connected! 192.168.1.226 Client connected Response: httpCRs { "headers": { "Date": "Tue, 04 Apr 2017 19:41:48 GMT", "Server": "Apache/2.4.18 (Ubuntu)", "Last-Modified": "Fri, 15 Nov 2013 15:42:26 GMT", "ETag": "\"d-4eb390b887c80\"", "Accept-Ranges": "bytes", "Content-Length": "13", "Connection": "close", "Content-Type": "text/plain" }, "httpVersion": "1.1", "statusCode": "200", "statusMessage": "OK" } --->Hello World! MQTT connection accepted {"topic":"test/espruino","message":"from server","dup":0,"qos":0,"retain":1} topic: test/espruino message: from server makeid: M95lA MQTT unsupported packet type: 5 [MQTT]80,2,0,1 makeid: vuVhs MQTT unsupported packet type: 5 [MQTT]80,2,0,1,208,0 makeid: X3K5K MQTT unsupported packet type: 5 [MQTT]80,2,0,1 makeid: 2ZZN3 MQTT unsupported packet type: 5 [MQTT]80,2,0,1,208,0 makeid: yG6HR MQTT unsupported packet type: 5 [MQTT]80,2,0,1 makeid: SSwc0 MQTT unsupported packet type: 5 [MQTT]80,2,0,1 makeid: UKyIs MQTT unsupported packet type: 5 [MQTT]80,2,0,1 makeid: NFBwM MQTT unsupported packet type: 5 [MQTT]80,2,0,1,208,0 makeid: SnxMM MQTT unsupported packet type: 5 [MQTT]80,2,0,1 makeid: aB2tu MQTT unsupported packet type: 5 [MQTT]80,2,0,1,208,0 >
Nothing in eMQ Console subscribed to test/#
-
• #20
There isn't QoS support in the MQTT client so that would be your problem in the latter tests. Because MQTT is running over a TCP/IP link which has QoS itself, there is no need to have it.
I've just made some changes to the MQTT library that will hopefully fix the problems you're having, so could you re-upload with the initial code and see if it is better?
Do you know what data you were sending initially? At least one of the problems seemed to stem from
parsePublish
being unable to parse the published data it was receiving - and about the only reason I could see for that was that the length of the topic and message together was just 1. -
• #21
Hi Gordon,
It seems that the clinet.on('data') is sending more than one message in the data item.
Here is a fix I have hacked for MQTT.js, couldn't find it on github for a pull request.
MQTT.prototype.connect = function(client) { var mqo = this; var onConnect = function() { console.log('Client connected'); client.write(mqo.mqttConnect(mqo.client_id)); mqo.partData = ''; // Disconnect if no CONNACK is received mqo.ctimo = setTimeout(function() { mqo.ctimo = undefined; mqo.disconnect(); }, mqo.C.CONNECT_TIMEOUT); // Set up regular keep_alive ping mqo.pintr = setInterval(function() { // console.log("Pinging MQTT server"); mqo.ping(); }, mqo.ping_interval*1000); // Incoming data client.on('data', function(data) { if (mqo.partData) { //console.log('** Adding PART DATA **'); data = mqo.partData + data; mqo.partData = ''; } var type = data.charCodeAt(0) >> 4; var rLen = data.charCodeAt(1); var pLen = rLen + 2; if (data.length < pLen) { mqo.partData = data; return; } var pData = data.substr(0,pLen); if(type === TYPE.PUBLISH) { var parsedData = parsePublish(pData); if (parsedData!==undefined) { mqo.emit('publish', parsedData); mqo.emit('message', parsedData.topic, parsedData.message); } } else if(type === TYPE.PUBACK) { // implement puback } else if(type === TYPE.SUBACK) { // implement suback } else if(type === TYPE.UNSUBACK) { // implement unsuback } else if(type === TYPE.PINGREQ) { // silently reply to pings client.write(TYPE.PINGRESP+"\x00"); // reply to PINGREQ } else if(type === TYPE.PINGRESP) { mqo.emit('ping_reply'); } else if(type === TYPE.CONNACK) { if (mqo.ctimo) clearTimeout(mqo.ctimo); mqo.ctimo = undefined; var returnCode = pData.charCodeAt(3); if(returnCode === RETURN_CODES.ACCEPTED) { mqo.connected = true; console.log("MQTT connection accepted"); mqo.emit('connected'); mqo.emit('connect'); } else { var mqttError = "Connection refused, "; switch(returnCode) { case RETURN_CODES.UNACCEPTABLE_PROTOCOL_VERSION: mqttError += "unacceptable protocol version."; break; case RETURN_CODES.IDENTIFIER_REJECTED: mqttError += "identifier rejected."; break; case RETURN_CODES.SERVER_UNAVAILABLE: mqttError += "server unavailable."; break; case RETURN_CODES.BAD_USER_NAME_OR_PASSWORD: mqttError += "bad user name or password."; break; case RETURN_CODES.NOT_AUTHORIZED: mqttError += "not authorized."; break; default: mqttError += "unknown return code: " + returnCode + "."; } console.log(mqttError); mqo.emit('error', mqttError); } } else { console.log("MQTT unsupported packet type: " + type); console.log("[MQTT]" + data.split("").map(function (c) { return c.charCodeAt(0); })); } if (data.length > pLen) { client.emit('data', data.substr(pLen)); } });
-
• #22
I have added some QoS handshake and some basic caching, need to get a replay after reconnect and drop old undelivered. See github https://github.com/srhart/MQTT
-
• #23
I'm publishing the same topic over and over again, using the node mqtt module on my computer, and occasionally I'm getting incomplete data printed out in Espruino. I assume the Espruino MQTT code is to blame because the client matched on the topic, yet the output doesn't match.
{ "topic": "sb_platform/v1/tes_16002b00", "message": "100", "dup": 0, "qos": 0, "retain": 0 } 100 Connection refused, unknown return code: 115. { "topic": "sb_platform/v1/tes_16002b00", "message": "100", "dup": 0, "qos": 0, "retain": 0 } 100 { "topic": "sb_platform/v1/tes_16002b00", "message": "100", "dup": 0, "qos": 0, "retain": 0 } 100 { "topic": "sb_platform/v1/tes_16002b00", "message": "100", "dup": 0, "qos": 0, "retain": 0 } 100 MQTT unsupported packet type: 0 [MQTT]0,27,115,98,95,112,108,97,116,102,111,114,109,47,118,49,47,116,101,115,95,49,54,48,48,50,98,48,48,49,48,48 { "topic": "sb_platform/v1/tes_16002b00", "message": "10", "dup": 0, "qos": 0, "retain": 0 } 10 { "topic": "sb_platform/v1/tes_16002b00", "message": "100", "dup": 0, "qos": 0, "retain": 0 } 100 { "topic": "sb_platform/v1/tes_16002b00", "message": "100", "dup": 0, "qos": 0, "retain": 0 } 100 { "topic": "sb_plat", "message": "", "dup": 0, "qos": 0, "retain": 0 } MQTT unsupported packet type: 6 [MQTT]102,111,114,109,47,118,49,47,116,101,115,95,49,54,48,48,50,98,48,48,103,111
-
• #24
I had the same issue, it seems that the default MQTT module sometimes gets a ping reply and the message in a single packet and is not separating the two. Did you try the updated library I posted on Github?
-
• #25
@user75453, I did. I didn't have success. Are you sure you pasted valid JS? I recall a closing brace was missing, and some other issues which lead me to give up on that approach.
Hello!
I'm trying to run mqtt client on my espruino. And have errors all the time. I tried to do it with options:
and as result got:
Without options I tried to connect with eclipse sandbox, and it works different:
Could I fix it somehow?