0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

MQTT: 受信したデータを Redis に入れる

Last updated at Posted at 2025-04-01

BROKER は localhost
TOPIC は /topic/register
です。

プログラム

subscribe_redis.py
#! /usr/bin/python
#
#	subscribe_redis.py
#
#						Mar/31/2025
#
# ------------------------------------------------------------------
import sys
import json
import paho.mqtt.subscribe as subscribe
import redis

# ------------------------------------------------------------------
def redis_write_proc(key,value):
#
	sys.stderr.write("*** redis_write_proc ***\n")
	rr = redis.Redis(host='localhost', port=6379, db=0)
	rr.set(key, value)
# ------------------------------------------------------------------
def on_message_print(client, userdata, message):
	print("%s %s" % (message.topic, message.payload))
	json_str = message.payload
	unit_aa = json.loads(json_str)
	cpid = unit_aa['cpid']
	version = unit_aa['version']
	print(cpid)
	print(version)
	key = "cpid:" + cpid
	redis_write_proc(key,version)
#
# ------------------------------------------------------------------
sys.stderr.write("*** 開始 ***\n")
#
broker = 'localhost'
port = 1883
topic = '/topic/register'
#
#
subscribe.callback(on_message_print, topic, hostname=broker, userdata={"message_count": 0})
#
sys.stderr.write("*** 終了 ***\n")
# ------------------------------------------------------------------

テスト用スクリプト

#
BROKER="localhost"
TOPIC="/topic/register"
#
echo $BROKER
message="{\"cpid\": \"A1B2C3D9\",\"version\": \"2025-3-31 AM 11:09\"}"
mosquitto_pub -d -m "${message}" \
    -h  $BROKER \
    --topic $TOPIC
#

Systemd でプログラムを動かす

プログラムを
/usr/local/subscribe に置く

サービスの作成

subscribe_redis.service
[Unit]
Description = start up mqtt_client subscribe_redis

[Service]
WorkingDirectory=/var/tmp/subscribe_redis
ExecStart=/usr/local/subscribe/subscribe_redis.py
Type=simple

[Install]
WantedBy=default.target

作業用の Directory を作成

mkdir /var/tmp/subscribe_redis

起動

sudo systemctl start subscribe_redis

起動の確認

sudo systemctl status subscribe_redis
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?