LoginSignup
10
10

More than 5 years have passed since last update.

春だ!IoTだ!sango経由でTesselとMQTTで通信だ!

Last updated at Posted at 2015-01-15

2015年でIoTがドカーンとアレで何かが凄いらしいのでTesselとサーバを通信させてあれこれ遊ぼうとしているんだけど、どうもTesselはネットワークとか色々弱いので低コストなプロトコルと評判のMQTTで通信してみる。
MQTTサーバ構築とかは面倒なのでsangoの無料のライトプランを利用。試してないけど、sangoじゃなくてもCloudMQTTとかでも似た感じだと思う。

publisher (tessel)

tessel-publisher.js
var mqtt = require("mqtt"),
    config = require("./config.json"),
    client = mqtt.createClient(config.port, config.host, config.options),
    tessel = require('tessel'),
    climate = require('climate-si7020').use(tessel.port['A']);

climate.on('ready', function ready() {
  console.log('climate ready');
  setInterval(function() {
    climate.readTemperature(function(err, temperature) {
      if (err) return;

      var msg = temperature.toString();
      console.log(msg);
      client.publish(config.topic + "/tessel", msg);
    });
  }, 20000);
});

こんな感じで気温を取ってきてpublishするだけのプログラムを作成。
MQTT部分はMQTT.jsを使った。2015/1/15時点での最新版は1.0.1なんだけど機能がだいぶ増えてて依存性も増えてるっぽいので、今回はv0.3.13を利用。Tesselはnode.jsとの互換性に割と難があるので、依存が増えると罠を踏みがち。

ユーザ情報とかの設定ファイルも安心と信頼の生json。こんな感じ。

config.json
{
  "host": "lite.mqtt.shiguredo.jp",
  "port": 1883,
  "options": {
    "username": "username@github",
    "password": "xxxxxx",
    "keepalive": 10000
  },
  "topic": "username@github"
}

subscriber (server)

subscriber.js
var mqtt = require("mqtt"),
    config = require("./config.json"),
    client = mqtt.createClient(config.port, config.host, config.options);

client.subscribe(config.topic + "/#");

client.on("message", function(topic, message) {
  console.log(topic, message.toString());
});

で、普通にサーバ側で動作させる、subscribeして受け取ったメッセージを出力するだけのプログラムを用意。こっちはなんでもいいんだけど、別に別言語にする理由もないのでnode.jsにした。設定ファイル使いまわせるし。

実行結果

publisher (tessel)

$ tessel run tessel-publisher.js 
TESSEL! Connected to TM-00-04-f0009a30-005e4f56-5cba6249.
INFO Bundling directory /Users/hogelog/repos/hogelog/js/hello-mqtt
INFO Deploying bundle (469.00 KB)...
INFO Running script...
climate ready
25
25
26

subscriber (server)

$ node subscriber.js 
hogelog@github/tessel 25
hogelog@github/tessel 25
hogelog@github/tessel 26

tesselが取得した気温情報をサーバ側で受け取れている。

ちょっと前、TesselとIRCプロトコルで通信してみようとアレコレめっちゃ苦労した結果不安定で無理だなーと諦めたんだけど、MQTT使ったら当然のように普通にあれこれ通信できて笑える。IoT向けなプロトコルとしても注目されてて、それを動作させるためにTesselの中の人も頑張ってるんだし当たり前かもしれないけど。時代はMQTT。

↑の方に書いたソースコードとかは https://github.com/hogelog/hello-mqtt-node に全部あります。

参考にしたページとか

10
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
10