From f769139ed409e0a115eded0b7d273209fbbada1d Mon Sep 17 00:00:00 2001 From: robert Date: Wed, 31 Jan 2024 23:27:26 +0000 Subject: [PATCH] change calling --- examples/solar-monitoring.py | 60 ++++++++++++++++++++++++------------ 1 file changed, 41 insertions(+), 19 deletions(-) diff --git a/examples/solar-monitoring.py b/examples/solar-monitoring.py index c8f3a6a..c406ccf 100644 --- a/examples/solar-monitoring.py +++ b/examples/solar-monitoring.py @@ -38,22 +38,37 @@ topic_car_soc = "openWB/vehicle/4/get/soc" topic_charge_point_power = "openWB/internal_chargepoint/0/get/powers" -try: - # create the MQTT client - client = mqtt_client.Client(client_id, protocol=mqtt_client.MQTTv31) # * set a random string (max 23 chars) +def connect_mqtt(): + def on_connect(client, userdata, flags, rc): + if rc == 0: + logging.info("Connected to MQTT Broker!") + else: + logging.info("Failed to connect, return code %d\n", rc) - # client connection - # client.username_pw_set(mqtt_username, mqtt_password) # MQTT server credentials - client.connect(mqtt_broker, 1883, 60) # MQTT server address + client = mqtt_client.Client(client_id) + # client.username_pw_set(username, password) + client.on_connect = on_connect + client.connect(broker, port) + return client - house_battery_soc = client.subscribe(topic_house_battery_soc) - house_battery_power = client.subscribe(topic_house_battery_power) - power_import_export = client.subscribe(topic_power_import_export) - pv_power = client.subscribe(topic_pv_power) - house_power = client.subscribe(topic_house_power) - car_soc = client.subscribe(topic_car_soc) - charge_point_power = client.subscribe(topic_charge_point_power) +def subscribe(client: mqtt_client, topic): + def on_message(client, userdata, msg): + print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic") + + client.subscribe(topic) + client.on_message = on_message + + +def run(): + client = connect_mqtt() + house_battery_soc = subscribe(topic_house_battery_soc) + house_battery_power = subscribe(topic_house_battery_power) + power_import_export = subscribe(topic_power_import_export) + pv_power = subscribe(topic_pv_power) + house_power = subscribe(topic_house_power) + car_soc = subscribe(topic_car_soc) + charge_point_power = subscribe(topic_charge_point_power) logging.info("epd2in13b_V3 Demo") @@ -89,11 +104,18 @@ try: logging.info("Goto Sleep...") epd.sleep() + + client.loop_forever() + + +if __name__ == '__main__': + run() + -except IOError as e: - logging.info(e) +#except IOError as e: +# logging.info(e) -except KeyboardInterrupt: - logging.info("ctrl + c:") - epd2in13b_V3.epdconfig.module_exit() - exit() +#except KeyboardInterrupt: +# logging.info("ctrl + c:") +# epd2in13b_V3.epdconfig.module_exit() +# exit()