Now is mqtt client main
authorNils ForssÃén <forssennils@gmail.com>
Tue, 5 Dec 2023 04:03:43 +0000 (05:03 +0100)
committerNils ForssÃén <forssennils@gmail.com>
Tue, 5 Dec 2023 04:03:43 +0000 (05:03 +0100)
main.py

diff --git a/main.py b/main.py
index 2429f030ffe8bcf499970c4e108a675931a76a45..e73eee36185abdd7df07411d77a22cc94ed49bcf 100755 (executable)
--- a/main.py
+++ b/main.py
@@ -1,11 +1,14 @@
 #!/usr/bin/env python3
 
 import requests
+import time
+from threading import Thread
 from bs4 import BeautifulSoup
 import datetime
 from dataclasses import dataclass
 import re
 import googleCalendar
+from paho.mqtt import client as mqtt_client
 
 headers = {
         "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36"
@@ -13,6 +16,17 @@ headers = {
 
 TIMEEDIT_URLS = ["https://cloud.timeedit.net/liu/web/schema/ri167XQQ618Z50Qm07060gZ6y6Y7509Q6Y95Y2.html"]
 
+MQTT_BROKER = "localhost"
+MQTT_PORT = 1883
+MQTT_TOPIC = "timeedit/request"
+MQTT_AVAIL_TOPIC = "timeedit/available"
+MQTT_CLIENT_ID = "timeedit_request_sub"
+
+MQTT_COMMAND = "run"
+WORKING_THREAD = None
+
+# nohup ~/scripts/timeedit_mqtt_client/main.py > /dev/null 2>&1 &
+
 
 @dataclass
 class event:
@@ -46,7 +60,7 @@ class event:
         return event
     
     
-def get_timeedit_events(session):
+def get_timeedit_events(session: list) -> list:
     for schedule_URL in TIMEEDIT_URLS:
         data = session.get(
             schedule_URL,
@@ -91,7 +105,7 @@ def get_timeedit_events(session):
     return schedule
 
     
-def reset_gc_events(schedule):
+def reset_gc_events(schedule) -> None:
     for c_event in googleCalendar.listEvents(
     **{
         "timeMin": "{0}T{1}{2}".format(
@@ -108,12 +122,66 @@ def reset_gc_events(schedule):
     for n_event in schedule:
         googleCalendar.createEvent(n_event.get_gc_event())
         print(f"Created: {n_event}\n")
+
+def handle_request(client, userdata, msg) -> None:
+    print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic.")
     
+    global WORKING_THREAD
     
-if __name__ == "__main__":
+    if (msg.payload.decode() == MQTT_COMMAND):
+        if (WORKING_THREAD is None or not WORKING_THREAD.is_alive()):
+            WORKING_THREAD = Thread(target=threaded_handle)
+            WORKING_THREAD.start()
+        else:
+            print(f"Not finished with previous command!")
+    else:
+        print(f"Unknown command: {msg.payload.decode()}")
     
-    with requests.session() as session:
+    
+    
+def on_connect(client, userdata, flags, rc):
+    if rc == 0:
+        print("Connected to MQTT Broker!")
+    else:
+        print("Failed to connect, return code %d", rc)
+    
+    subscribe(client)
         
+    
+def connect_mqtt() -> mqtt_client:
+
+    client = mqtt_client.Client(MQTT_CLIENT_ID)
+    
+    client.will_set(MQTT_AVAIL_TOPIC, payload="dead", qos=0, retain=True)
+    
+    client.on_connect = on_connect
+    client.connect_async(MQTT_BROKER, MQTT_PORT, keepalive=3600)
+    
+    return client
+
+
+def subscribe(client) -> None:
+    client.subscribe(MQTT_TOPIC, qos=0)
+    client.on_message = handle_request
+
+
+def threaded_handle() -> None:
+    print("Working thread started!")
+
+    with requests.session() as session:
         timeedit_schedule = get_timeedit_events(session)
 
     reset_gc_events(timeedit_schedule)
+    
+    print("Working thread finished!")
+
+if __name__ == "__main__":
+    client = connect_mqtt()
+    client.loop_start()
+    
+    # Wait for thread to start before sending birth pub
+    time.sleep(1)
+    client.publish(MQTT_AVAIL_TOPIC, payload="alive", qos=0, retain=True)
+    
+    while(1):
+        time.sleep(1)
\ No newline at end of file