LoginSignup
1

More than 1 year has passed since last update.

MQTT を file に変換するプログラム

Last updated at Posted at 2021-08-22

次のシステムを構築する常駐プログラムです。
Grove IoT スターターキット for SORACOM で作るリモートカメラシステム

mqtt_to_file.py
#! /usr/bin/python3
#
#   mqtt_to_file.py
#
#                   Aug/22/2021
# ------------------------------------------------------------------
import paho.mqtt.client as mqtt
import json

MQTT_HOST = "www2.ekzemplaro.org"
MQTT_TOPIC = "sample/imageTopic"
MQTT_PORT = 1883
MQTT_KEEP_ALIVE = 60
#
# ------------------------------------------------------------------
def on_connect(mqttc, obj, flags, rc):
    print("rc: " + str(rc))
#
# ------------------------------------------------------------------
def file_write_proc(file_name,str_out):
#
    fp_out = open(file_name,mode='w',encoding='utf-8')
    fp_out.write(str_out)
    fp_out.close()
# ------------------------------------------------------------------
def on_message(mqttc, obj, msg):
    file_name = "/var/tmp/mqtt_work/status.json"
#
    print(msg.topic + " " + str(msg.qos))
    str_out = msg.payload.decode()
    print(len(str_out))
#
    if len(str_out) < 100:
        print(str_out)
#
    unit_aa = json.loads(str_out)
    if "button" in unit_aa:
        print(unit_aa["button"])
        if (unit_aa["button"] == "on"):
            file_write_proc(file_name,str_out)
    elif "status" in unit_aa:
        print(unit_aa["status"])
        file_write_proc(file_name,str_out)
# ------------------------------------------------------------------
mqttc = mqtt.Client()
mqttc.on_message = on_message
mqttc.on_connect = on_connect
mqttc.connect(MQTT_HOST, MQTT_PORT, MQTT_KEEP_ALIVE)
mqttc.subscribe(MQTT_TOPIC)

mqttc.loop_forever()
# ------------------------------------------------------------------

実行時の様子

$ ./mqtt_to_file.py 
rc: 0
sample/imageTopic 0
16
{"button":"off"}
off
sample/imageTopic 0
15
{"button":"on"}
on
sample/imageTopic 0
16
{"button":"off"}
off

systemd で常駐化する。

ワンショットサービスの作成

/opt/one_shot/one_shot.sh
#!/bin/bash
#
#   one_shot.sh
#
LOG_FILE="/tmp/one_shot.log"
date >> $LOG_FILE
/var/www/html/mqtt/mqtt_to_file/mqtt_to_file.py >> $LOG_FILE
echo "one_shot" >> $LOG_FILE
date >> $LOG_FILE
#
/etc/systemd/system/one_shot.service
[Unit]
Description=one_shot shell
After=netctl@profile.service

[Service]
# Environment=NODE_PORT=3000
Type=simple
User=www-data
Restart=on-failure
ExecStart=/bin/bash /opt/one_shot/one_shot.sh
WorkingDirectory=/tmp

[Install]
WantedBy=multi-user.target

起動

sudo systemctl start one_shot

OS再起動で起動するように設定

sudo systemctl enable one_shot

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
1