diff options
-rw-r--r-- | shop2mqtt/.gitignore | 2 | ||||
-rw-r--r-- | shop2mqtt/README.md | 17 | ||||
-rwxr-xr-x | shop2mqtt/sendStock2Mqtt.py | 39 | ||||
-rw-r--r-- | shop2mqtt/shop2mqtt.conf.example | 10 |
4 files changed, 68 insertions, 0 deletions
diff --git a/shop2mqtt/.gitignore b/shop2mqtt/.gitignore new file mode 100644 index 0000000..1e25736 --- /dev/null +++ b/shop2mqtt/.gitignore @@ -0,0 +1,2 @@ +.idea/ +shop2mqtt.conf diff --git a/shop2mqtt/README.md b/shop2mqtt/README.md new file mode 100644 index 0000000..9627e82 --- /dev/null +++ b/shop2mqtt/README.md @@ -0,0 +1,17 @@ +# Setup + +You need the python3 paho-mqtt lib. E.g. +``` +sudo apt-get install python3-paho-mqtt +``` + +Create the config from the example: +``` +cp shop2mqtt.conf.example shop2mqtt.conf +``` +and change the config to your needs. + + +# Run + +Just run `./sendStock2Mqtt.py` or use cron.
\ No newline at end of file diff --git a/shop2mqtt/sendStock2Mqtt.py b/shop2mqtt/sendStock2Mqtt.py new file mode 100755 index 0000000..a54675d --- /dev/null +++ b/shop2mqtt/sendStock2Mqtt.py @@ -0,0 +1,39 @@ +#!/usr/bin/python3 +import configparser +import json +import os +import sqlite3 +import ssl + +from paho.mqtt import publish + + +def get_current_stock(shop_config): + db_file = shop_config["shop_db"] + if not os.path.isfile(db_file): + print("Shop db not found: %s" % db_file) + exit(1) + conn = sqlite3.connect(db_file) + c = conn.cursor() + + data = [] + for row in c.execute('SELECT name, amount FROM products WHERE deprecated = 0 AND amount > 0'): + data.append(row) + + return data + + +def send_to_mqtt(mqtt_config, payload): + publish.single(mqtt_config["topic"], payload, + hostname=mqtt_config["host"], port=int(mqtt_config["port"]), + auth={'username': mqtt_config["username"], 'password': mqtt_config["password"]}, + tls={'ca_certs': mqtt_config["host_cert"], 'tls_version': ssl.PROTOCOL_TLS, 'insecure': False}, + client_id="send2Stock2Mqtt") + + +if __name__ == '__main__': + config = configparser.ConfigParser() + config.read("shop2mqtt.conf") + + stock_data = get_current_stock(config["shop"]) + send_to_mqtt(config["mqtt"], json.dumps(stock_data, indent=None, separators=(',', ':'))) diff --git a/shop2mqtt/shop2mqtt.conf.example b/shop2mqtt/shop2mqtt.conf.example new file mode 100644 index 0000000..39aece5 --- /dev/null +++ b/shop2mqtt/shop2mqtt.conf.example @@ -0,0 +1,10 @@ +[mqtt] +host = spacegate.mainframe.lan +host_cert = spacegate.cert.pem +port = 8883 +username = shop +password = ... +topic = /shop/stock + +[shop] +shop_db = ../shop.db
\ No newline at end of file |