Skip to content

Instantly share code, notes, and snippets.

@dceejay
Created February 8, 2014 13:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dceejay/7218a027cfff86164dea to your computer and use it in GitHub Desktop.
Save dceejay/7218a027cfff86164dea to your computer and use it in GitHub Desktop.
MQTT-SN buffer formatter

Simple function to take a msg.payload and msg.topic and create an MQTT-SN QoS -1 buffer out of them. This can then be sent to a udp output node.

[{"id":"1a1e4cfb.7d15a3","type":"udp out","name":"","addr":"localhost","iface":"","port":"1881","base64":false,"multicast":"false","x":497.1666450500488,"y":137.16667652130127,"z":"f8cf4ab6.9daa1","wires":[]},{"id":"9f41705a.8cc57","type":"function","name":"MQTT-SN sender","func":"// Takes a payload and topic and makes a QoS -1\n// MQTT-SN message buffer out of it.\n\nfunction makeMqttsBuffer(topic,message) {\n var buf;\n var p=0;\n var len = topic.length + message.length + 7;\n if (len > 254) {\n p=2;\n buf = new Buffer(topic.length + message.length + 7 + p);\n buf[0] = 1;\n buf[1] = parseInt((len+p)/256);\n buf[2] = parseInt((len+p)%256);\n }\n else {\n buf = new Buffer(topic.length + message.length + 7 + p);\n buf[0] = len;\n }\n buf[1+p] = 12;\n buf[2+p] = 96;\n buf[3+p] = parseInt(topic.length/256);\n buf[4+p] = parseInt(topic.length%256);\n buf[5+p] = 32;\n buf[6+p] = 32;\n for (var i = 0; i < topic.length ; i++) {\n buf[7+i+p] = topic.charCodeAt(i);\n }\n for (var i = 0; i < message.length ; i++) {\n buf[7+topic.length+i+p] = message.charCodeAt(i);\n }\n return buf;\n}\n\nmsg.payload = makeMqttsBuffer(msg.topic, msg.payload);\n\nreturn msg;","outputs":1,"x":300.1666488647461,"y":153.1667079925537,"z":"f8cf4ab6.9daa1","wires":[["1a1e4cfb.7d15a3","900d38f6.292c38"]]},{"id":"452f99b.2c75ce8","type":"inject","name":"","topic":"Hello","payload":"Dave","payloadType":"string","repeat":"","crontab":"","once":false,"x":124.16667175292969,"y":167.1666717529297,"z":"f8cf4ab6.9daa1","wires":[["9f41705a.8cc57"]]},{"id":"900d38f6.292c38","type":"debug","name":"","active":false,"complete":false,"x":472.1666564941406,"y":189.1666717529297,"z":"f8cf4ab6.9daa1","wires":[]}]
@njh
Copy link

njh commented Jan 23, 2018

Was just thinking about making something like this. Awesome!

I wonder if this technique could be used both send and receive UDP packets - resulting in an MQTT to MQTT-SN QoS -1 bridge to (very) dumb devices.

@MartinSokolov15
Copy link

Hi, is there any example of data speed comparison between MQTT vs MQTT-SN ?

@dceejay
Copy link
Author

dceejay commented Oct 14, 2021

it's just bytes on the wire in single udp packets so it may be faster than tcp - but may be less reliable.

@martin9115
Copy link

Can we test energy consumption for MQTT vs MQTT-SN ?

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