Bye Bye Moore

PoCソルジャーな零細事業主が作業メモを残すブログ

Mosquittoをwebsocket対応にさせる その1:環境構築

Mosquittoをwebsocket対応にさせ、通信内容をブラウザに表示させます。

brewで環境を観に行くと、いかのような記述が。

$ brew info mosquitto
mosquitto: stable 1.4.14 (bottled)
Message broker implementing the MQTT protocol
https://mosquitto.org/
/usr/local/Cellar/mosquitto/1.4.14_1 (33 files, 630.0KB) *
  Poured from bottle on 2017-10-05 at 23:55:29
From: https://github.com/Homebrew/homebrew-core/blob/master/Formula/mosquitto.rb
==> Dependencies
Build: pkg-config ✘, cmake ✘
Required: c-ares ✔, openssl ✔
Recommended: libwebsockets ✔
==> Options
--without-libwebsockets
	Build without libwebsockets support
==> Caveats
mosquitto has been installed with a default configuration file.
You can make changes to the configuration by editing:
    /usr/local/etc/mosquitto/mosquitto.conf

To have launchd start mosquitto now and restart at login:
  brew services start mosquitto
Or, if you don't want/need a background service you can just run:
  mosquitto -c /usr/local/etc/mosquitto/mosquitto.conf

というわけで、編集しに行きます。
後々面倒なので、バックアップを。

$ cp /usr/local/etc/mosquitto/mosquitto.conf /usr/local/etc/mosquitto/mosquitto.conf.bak
$ cp /usr/local/etc/mosquitto/mosquitto.conf /usr/local/etc/mosquitto/my_mosquitto.conf

で、こんな感じで編集します。

$ diff /usr/local/etc/mosquitto/my_mosquitto.conf /usr/local/etc/mosquitto/mosquitto.conf.bak 
277c277
< listener 1883
---
> #listener
297,299c297
< listener 9090 127.0.0.1
< protocol websockets
< 
---
> #protocol mqtt

フツーに起動するといつも通りですが

$ mosquitto
1508255934: mosquitto version 1.4.14 (build date 2017-09-30 02:42:20+0100) starting
1508255934: Using default config.
1508255934: Opening ipv6 listen socket on port 1883.
1508255934: Opening ipv4 listen socket on port 1883.

"-c"オプションで先程設定してやったファイルを読むと、ちゃんとwebcocketが開きます

$ mosquitto -c /usr/local/etc/mosquitto/my_mosquitto.conf
1508257023: mosquitto version 1.4.14 (build date 2017-09-30 02:42:20+0100) starting
1508257023: Config loaded from /usr/local/etc/mosquitto/my_mosquitto.conf.
1508257023: Opening ipv6 listen socket on port 1883.
1508257023: Opening ipv4 listen socket on port 1883.
1508257023: Opening websockets listen socket on port 9090.

macOSでホスト名を設定する

macOSでホスト名を設定したい場合、" /private/etc/hosts"を弄ります。

実際のところ

検証環境

具体的なはなし

"/private/etc/hosts"を編集権限で弄ります。
ローカルホストの次に設定してやるといいでしょう。

$ cat /private/etc/hosts
##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting.  Do not change this entry.
##
127.0.0.1	localhost
255.255.255.255	broadcasthost
::1             localhost 
127.0.0.1	shuzo.mqtt.jp

diffで比較すると一応同じものが返ってきてることが分かります。
結構、遅いですが。

$ diff <(curl localhost) <(curl shuzo.mqtt.jp)
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  2700    0  2700    0     0   144k      0 --:--:-- --:--:-- --:--:--  146k
100  2700    0  2700    0     0    485      0 --:--:--  0:00:05 --:--:--   670
$

【読書メモ】火星の人類学者―脳神経科医と7人の奇妙な患者

火星の人類学者―脳神経科医と7人の奇妙な患者 (ハヤカワ文庫NF)

火星の人類学者―脳神経科医と7人の奇妙な患者 (ハヤカワ文庫NF)


フォローしているbotの中の人が、こんな投稿をしてました。

いくつか知ってるSFものの中に「火星の人類学者」という初めて見るタイトルが。
初見ではSFものかと思いましたが、違います。
医学エッセイという、全く馴染みの無い分野。

作者は神経学の方で、クライアントもその分野が解決のいとぐちになるのでは……と来た方々。
表題の"火星の人類学者"さんは自閉症の動物学者で、自分を評価するとそう表現できる、と語っています。

症例という大雑把な箱に放り込んでオシマイ……ではなく、
ちゃんと患者ご本人と相対しましょう、人間の心持ちで変わる事は多いといった趣旨です。
なんだかアドラー先生の話を思い出しますね。
shuzo-kino.hateblo.jp

BottleでWebsocketする

なんどか紹介しているPython製軽量WEB鯖Bottleで、Websocketを扱う方法です。

実際のところ

環境導入

$ pip install bottle-websocket

サンプル実行

公式提供のサンプルはgithubにあります。
実行には別途、geventという並行処理系ライブラリが必要です。

$ pip install gevent
$ pip install gevent-websocket

まず、python
"echo.py"

from bottle import get, run, template
from bottle.ext.websocket import GeventWebSocketServer
from bottle.ext.websocket import websocket

@get('/')
def index():
    return template('index')

@get('/websocket', apply=[websocket])
def echo(ws):
    while True:
        msg = ws.receive()
        if msg is not None:
            ws.send(msg)
        else: break

run(host='127.0.0.1', port=8080, server=GeventWebSocketServer)

つぎにフロントエンド"index.tpl"

<!doctype html>
<head>
    <meta charset="utf-8" />
    <title>WebSocket Echo Test</title>

    <style>
        li { list-style: none; }
    </style>

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
    <script>
        $(document).ready(function() {
            if (!window.WebSocket) {
                if (window.MozWebSocket) {
                    window.WebSocket = window.MozWebSocket;
                } else {
                    $('#messages').append("<li>Your browser doesn't support WebSockets.</li>");
                }
            }
            ws = new WebSocket('ws://127.0.0.1:8080/websocket');
            ws.onopen = function(evt) {
                $('#messages').append('<li>WebSocket connection opened.</li>');
            }
            ws.onmessage = function(evt) {
                $('#messages').append('<li>' + evt.data + '</li>');
            }
            ws.onclose = function(evt) {
                $('#messages').append('<li>WebSocket connection closed.</li>');
            }
            $('#send').submit(function() {
                ws.send($('input:first').val());
                $('input:first').val('').focus();
                return false;
            });
        });
    </script>
</head>
<body>
    <h2>Bottle Websockets!</h2>
    <form id="send" action='.'>
        <input type="text" value="message" />
        <input type="submit" value="Send" />
    </form>
    <div id="messages"></div>
</body>
</html>

実行はフツーのbottle同様、本体を実行するだけ。

$ python echo.py

gobotでmqtt

本文執筆中

package main

import (
  "gobot.io/x/gobot"
  "gobot.io/x/gobot/platforms/mqtt"
  "fmt"
  "time"
)

func main() {
  mqttAdaptor := mqtt.NewAdaptor("tcp://{{YOURIP}}:1883", "pinger")

  work := func() {
    mqttAdaptor.On("hello", func(msg mqtt.Message) {
      fmt.Println(msg)
    })
    mqttAdaptor.On("hola", func(msg mqtt.Message) {
      fmt.Println(msg)
    })
    data := []byte("o")
    gobot.Every(1*time.Second, func() {
      mqttAdaptor.Publish("hello", data)
    })
    gobot.Every(5*time.Second, func() {
      mqttAdaptor.Publish("hola", data)
    })
  }

  robot := gobot.NewRobot("mqttBot",
    []gobot.Connection{mqttAdaptor},
    work,
  )

  robot.Start()
}

参考もと

MQTT with Gobot

"found packages hoge (fuga.go) and main (sample.go) in"とか出たら、mainが複数呼ばれてる可能性が

"found packages hoge (fuga.go) and main (sample.go) in"とか出たら、mainが複数呼ばれてる可能性があります。
mainは複数存在できませんからね。

実際のところ

つい先日までフツーに動いていたGOスクリプトを機会があってもう一度動かそうとしたら、
以下のようなエラーが。

$ go run firmata_servo.go 
firmata_servo.go:11:2: found packages gobot (adaptor.go) and main (sample.go) in /Users/shuzo_kino/dev/src/gobot.io/x/gobot

前者のadaptor.goはインターフェイスの定義だったのでまぁいいのですが……sample.goとは一体???

何のことはなく……

  • 動作チェック用にsample.goという検証スクリプトを用意
  • その保存先がライブラリのディレクトリ直下
  • 日をおいて別のスクリプトからライブラリを読んだところmainが複数という奇っ怪な状況が発生

……という事のようです。

みなさん、横着せずスクリプトは新規の場所に置きましょう(戒め

Arduino on ESP32 でMQTTの実験をしてみる その4:ESP32でsubmitする

shuzo-kino.hateblo.jp
では送信をやりました。
次は受信です。

実際のところ

動作環境

スクリプト

前回と同様、以下をベースにします。
pubsubclient/mqtt_esp8266.ino at master · knolleary/pubsubclient · GitHub
アスキーの"0"をおくると消灯、それ以外は点灯というロジックです。

#include <WiFi.h>
#include <PubSubClient.h>

// Update these with values suitable for your network.

const char* ssid = "YOUR_SSID";
const char* password = "YOUR_PASS";
const char* mqtt_server = "YOUR_ACCOUNT/IP";

WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;

void setup_wifi() {

  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  randomSeed(micros());

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();

  // Switch on the LED if an 1 was received as first character
  if ((char)payload[0] == '1') {
    digitalWrite(LED_BUILTIN, LOW); 
    Serial.println("coming here");
  } else {
    digitalWrite(LED_BUILTIN, HIGH); 
  }

}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP32Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str())) {
      Serial.println("connected");
      client.subscribe("msg/led");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);     // Initialize the BUILTIN_LED pin as an output
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
}

void loop() {

  if (!client.connected()) {
    reconnect();
  }
  client.loop();
}

動作ログ

初期接続に成功すると、mosquittoの方には、こんな感じで接続情報がきます

1507644406: New connection from YOUR_ACCOUNT/IP on port 1883.
1507644406: New client connected from ARDUINO_IP as ESP32Client-1f85 (c1, k15).

この状態からpublisherで以下のような感じで送ると……

$ mosquitto_pub -h YOUR_ACCOUNT/IP -t msg/comment -m 1 -q 1
$ mosquitto_pub -h YOUR_ACCOUNT/IP -t msg/comment -m 1 -q 1
$ mosquitto_pub -h YOUR_ACCOUNT/IP -t msg/comment -m 0 -q 1
$ mosquitto_pub -h YOUR_ACCOUNT/IP -t msg/comment -m 1 -q 1
...

Arduino側のシリアルにはこんな感じでログが出でて、
LEDの方もちゃんと突いたり消えたりしてくれます。

Connecting to YOURSSID
.....
WiFi connected
IP address: 
YOUR_ACCOUNT/IP
Attempting MQTT connection...connected
Message arrived [msg/led] 1
coming here
Message arrived [msg/led] 1
coming here
Message arrived [msg/led] 0
Message arrived [msg/led] 1
coming here
...