Created
October 2, 2024 04:57
-
-
Save ksasao/bc1213242ec7e0bedb9a6da419ded4df to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# シリアルポートで受信したデータを MQTT Broker に投げる | |
from paho.mqtt import client as mqtt_client | |
import random | |
import time | |
import asyncio | |
from serial_asyncio import open_serial_connection | |
import sys | |
args = sys.argv | |
name = args[1] # COM3 などを引数で指定する (例: python serial2mqtt.py COM3 ) | |
broker = 'localhost' # MQTT Brokerのホスト | |
port = 1883 | |
client_id = f'python-mqtt-{name}-{random.randint(0, 1000)}' | |
print(f"{name} = {client_id}") | |
def connect_mqtt(): | |
def on_connect(client, userdata, flags, rc): | |
if rc == 0: | |
print("Connected to MQTT Broker!") | |
else: | |
print("Failed to connect, return code %d\n", rc) | |
# Set Connecting Client ID | |
client = mqtt_client.Client(client_id) | |
# client.username_pw_set(username, password) | |
client.on_connect = on_connect | |
client.connect(broker, port) | |
return client | |
async def main(): | |
client = connect_mqtt() | |
client.loop_start() | |
reader, writer = await open_serial_connection(url=name, baudrate=115200) | |
while True: | |
line = await reader.readline() | |
# topic と message に分ける | |
data = str(line).split(' ') | |
if len(data) == 2 and data[1][0] == '{': | |
# 文字列を無理やり加工している部分をなおす | |
topic = str(data[0])[2:] | |
msg = str(data[1]).replace("\\r\\n","")[0:-1] | |
result = client.publish(topic, msg) | |
status = result[0] | |
if status == 0: | |
print(f"{topic}\t{msg}") | |
else: | |
print(f"Error: {line}") | |
else: | |
print(f"Skipped: {line}") | |
asyncio.run(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment