Skip to content

Commit

Permalink
refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
vladak committed Dec 2, 2023
1 parent 23dba63 commit 7a2b952
Showing 1 changed file with 22 additions and 13 deletions.
35 changes: 22 additions & 13 deletions demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,6 @@ def get_device_state(device_info, args):
return state


# pylint: disable=too-many-statements,too-many-locals
def main():
"""
Main loop. Acquire state from plugs using MQTT and use a threshold to determine
Expand All @@ -176,33 +175,43 @@ def main():
# map of device name to Devices instance
devices = {}

# connect to MQTT broker
mqtt = mqtt_setup(args, devices)

i = 0
while True:
# Make sure to stay connected to the broker e.g. in case of keep alive.
i += 1
logger.debug(f"Loop {i}")
mqtt.loop(1)

for device_name, device_info in devices.items():
logger.debug(f"{device_info}")
logger.info(f"{device_name} = {get_device_state(device_info, args)}")


def mqtt_setup(args, devices):
"""
connect to MQTT broker and subscribe to topic given by the args
"""
logger = logging.getLogger(__name__)

mqtt = MQTT.MQTT(
broker=args.hostname,
port=args.port,
socket_pool=socket,
ssl_context=ssl.create_default_context(),
user_data=devices,
)

mqtt.on_connect = connect
mqtt.on_subscribe = subscribe
mqtt.on_message = message

logger.info(f"Connecting to MQTT broker {args.hostname} on port {args.port}")
mqtt.connect()
mqtt.subscribe(args.topic, qos=0)

i = 0
while True:
# Make sure to stay connected to the broker e.g. in case of keep alive.
i += 1
logger.debug(f"Loop {i}")
mqtt.loop(1)
mqtt.subscribe(args.topic, qos=0)

for device_name, device_info in devices.items():
logger.debug(f"{device_info}")
logger.info(f"{device_name} = {get_device_state(device_info, args)}")
return mqtt


if __name__ == "__main__":
Expand Down

0 comments on commit 7a2b952

Please sign in to comment.