Commit 0b461fec authored by John, Fabian's avatar John, Fabian
Browse files

added wrapper for serial port to mqtt in first version

parents
.idea/
config.json
log.txt
[[source]]
url = "https://pypi.org/simple"
verify_ssl = true
name = "pypi"
[packages]
paho-mqtt = "==1.5.1"
pyserial = "==3.5"
[dev-packages]
[requires]
python_version = "3.7"
{
"_meta": {
"hash": {
"sha256": "f8106fc3c02eec4f6f09d02a65e2d2e152fcc8c9cd241fad260074c399e26bf8"
},
"pipfile-spec": 6,
"requires": {
"python_version": "3.7"
},
"sources": [
{
"name": "pypi",
"url": "https://pypi.org/simple",
"verify_ssl": true
}
]
},
"default": {
"paho-mqtt": {
"hashes": [
"sha256:9feb068e822be7b3a116324e01fb6028eb1d66412bf98595ae72698965cb1cae"
],
"index": "pypi",
"version": "==1.5.1"
},
"pyserial": {
"hashes": [
"sha256:3c77e014170dfffbd816e6ffc205e9842efb10be9f58ec16d3e8675b4925cddb",
"sha256:c4451db6ba391ca6ca299fb3ec7bae67a5c55dde170964c7a14ceefec02f2cf0"
],
"index": "pypi",
"version": "==3.5"
}
},
"develop": {}
}
import json
import logging
import paho.mqtt.client as mqtt
import serial
from enum import Enum
__CompanyName__ = "Technische Hochschule Luebeck, FB E&I, Center of Excellence CoSA"
__FileDescription__ = "This program forwards uart messages to a dedicated serial port"
__version__ = "1.0.0"
__author__ = "Fabian John"
__FileVersion__ = __version__
__InternalName__ = "SerialMqttWrapper"
__LegalCopyright__ = "\xa9 Technische Hochschule Luebeck. All rights reserved."
__OriginalFilename__ = "SerialMqttWrapper.exe"
__ProductName__ = "SerialMqttWrapper"
__ProductVersion__ = __version__
class ser_lf(int, Enum):
CR: int = 1
LF: int = 2
CRLF: int = 3
def print_version_info():
logging.info(
"\n########################################\n" + __ProductName__ + " Version: " + __version__ + "\n" + __LegalCopyright__ + "\n" + __author__ + "\n" + __CompanyName__ + "\n\nDescription: " + __FileDescription__ + "\n########################################\n")
# --------------------------------------------
# READING configuration and stuff
# alter the XXX_example_stuff to your needs
# --------------------------------------------
try:
with open('config.json') as config_file:
cfg = json.load(config_file)
except:
# generate standard config file if no file is present
cfg = {
'mqtt': {
'broker_ip': "169.254.251.12",
'root_topic': "cosa/lab/serial1/"
},
'serial': {
'port': "Com8", #ttyUSB0 for tag
'baud': 9600,
'lf': ser_lf.CRLF
},
# ---------------------------
# take logging as it is
# Levels:
# FATAL = 50
# ERROR = 40
# WARNING = 30
# INFO = 20
# DEBUG = 10
# ---------------------------
'logging': {
'level': logging.DEBUG,
'filename': "log.txt",
'console': True,
'format': "%(asctime)s %(levelname)s: %(message)s"
}
}
with open('config.json', 'w') as f:
json.dump(cfg, f)
lf_chr = b'\r\n'
if cfg['serial']['lf'] == ser_lf.CR:
lf_chr = b'\r'
elif cfg['serial']['lf'] == ser_lf.LF:
lf_chr = b'\n'
# ------------------------------
# STARTING APPLICATION
# Use this section as it is
# ------------------------------
if cfg['logging']['console']:
logging.basicConfig(level=cfg['logging']['level'], format=cfg['logging']['format'])
else:
logging.basicConfig(filename=cfg['logging']['filename'], filemode='w', level=cfg['logging']['level'],
format=cfg['logging']['format'])
if cfg['logging']['console']:
ch = logging.StreamHandler()
ch.setLevel(cfg['logging']['level'])
print_version_info()
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
logging.info("MQTT connected")
client.subscribe(cfg['mqtt']['root_topic'] + "send_message")
client.subscribe(cfg['mqtt']['root_topic'] + "config")
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
logging.debug("Received Topic: " + msg.topic + " | Message: " + str(msg.payload))
logging.debug("Redirect Message to COM-Port: " + str(msg.payload))
global ser
ser.write(msg.payload + lf_chr)
logging.basicConfig(level=logging.DEBUG, format="%(asctime)s %(levelname)s: %(message)s")
# Preparing MQTT client
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
logging.debug("Try to connect MQTT")
client.connect("127.0.0.1", 1883, 60)
while not client.is_connected():
client.loop(1)
logging.debug("establishing serial connection")
ser = serial.Serial(timeout=1)
ser.baudrate = cfg['serial']['baud']
ser.port = cfg['serial']['port']
ser.open()
while not ser.is_open:
client.loop(1)
b_rec = b''
while True:
b_rec += ser.read_until(chr(lf_chr[len(lf_chr)-1]))
if len(b_rec) > 1:
if chr(b_rec[len(b_rec)-1]) == chr(lf_chr[len(lf_chr)-1]):
client.publish(cfg['mqtt']['root_topic'] + "raw", b_rec)
b_rec = b''
client.loop(.1)
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment