From 93a05b5de5d5d2bcb5d6b0c60f55d7d926c3ffff Mon Sep 17 00:00:00 2001 From: Holger Cremer Date: Sat, 15 Dec 2018 19:06:15 +0100 Subject: adds a script thats sends product stats to mqtt --- shop2mqtt/.gitignore | 2 ++ shop2mqtt/sendStock2Mqtt.py | 39 +++++++++++++++++++++++++++++++++++++++ shop2mqtt/shop2mqtt.conf.example | 10 ++++++++++ 3 files changed, 51 insertions(+) create mode 100644 shop2mqtt/.gitignore create mode 100755 shop2mqtt/sendStock2Mqtt.py create mode 100644 shop2mqtt/shop2mqtt.conf.example 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/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 -- cgit v1.2.3