Skip to content
Philippe Coval edited this page Jan 16, 2023 · 5 revisions

MQTT

IOTJS

IoT.js is supporting MQTT protocol, so it's straight forward to build a bridge:

Example:

mqtt

Resources:

SYSTEMD:

Bridge can be installed on Gateway itself along IoTjs, along MQTT broker:

ssh pi@gateway.local
sudo apt-get install mosquitto

Then service can be started on boot using this scriptlet:

First set some variables we will use in our script:

unit="rzr-webthing-example-iotjs-mqtt-level"
unit='webthing-example'
dir="${HOME}/usr/local/opt/$unit"
srcdir="${dir}/src/${unit}"
exe="$dir/$unit.sh"
service="$dir/$unit.service"
sudo=sudo
url=https://github.com/rzr/$unit
branch="iotjs/mqtt/level/master"
web_url="https://github.com/rzr/${unit}/tree/${branch}"
mqtt_host=localhost
mqtt_port=1883
httpd_port=8888
property="level"
mqtt_topic="${branch}/${property}" # TODO update with yours
json_url="http://localhost:${httpd_port}/"
property_url="http://localhost:${httpd_port}/properties/${property}"

Create luncher script (keep pasting):

$sudo mkdir -p "$dir"
    cat<<EOF | $sudo tee $exe && $sudo chmod a+rx $exe
#!/bin/sh
set -x
set -e
# TODO: service should wait DCHP answer
ip addr show
ping -c 1 1.1.1.1 || sleep 10 && echo "warning: offline"
curl http://ifconfig.io/all

if [ ! -d ${srcdir} ] ; then
  rm -rf "${srcdir}.tmp"
  mkdir -p "${srcdir}.tmp"
  git clone --depth 1 ${url} -b ${branch} "${srcdir}.tmp"
  mv "${srcdir}.tmp" "${srcdir}"
fi

make \
 -C ${srcdir} \
 start \
 port="${httpd_port}" \
 mqtt_host="${mqtt_host}" \
 mqtt_port="${mqtt_port}" \
 mqtt_topic="${mqtt_topic}" \
 mqtt_topic_key=${mqtt_topic_key} \
 #EOL
EOF

Create systemd service:

cat<<EOF | sudo tee "$service"
[Unit]
Description=$unit $branch $property
Documentation=${url}/tree/$branch
After=network-online.target
Wants=network-online.target
Before=mozilla-iot-gateway.target

[Service]
ExecStart=$exe
User=pi
Restart=always

[Install]
WantedBy=multi-user.target
EOF

Install and start it:

sudo chmod 644 $service
sudo systemctl daemon-reload
sudo systemctl link $service || sudo systemctl enable $service
sudo systemctl enable $unit
sudo systemctl daemon-reload
sudo reboot

It should be started on boot.

$sudo sync \
	&& $sudo systemctl status $unit \
	    || sudo journalctl -u $unit -xe --no-pager

Make sure it is working as expected:

${unit} - $unit
   Loaded: loaded (.../${unit}.service; enabled; vendor preset: enabled)
   Active: inactive (dead)

NATIVE:

Note that some MCU platforms (TizenRT, Arduino) are also supporting MQTT API, so MQTT can be used in device firmware too.

MORE:

Then it could be a good exercise to port nanomsg to IoT.js, and then make an adapter Addons for moziot Gateway, the other simpler approach is to use nodejs (I can share ported code ask me)

And then next one can try to do a RUST version:

LICENSE:

INDEX

Clone this wiki locally