-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstate_machine_mqtt.py
More file actions
51 lines (40 loc) · 1.12 KB
/
state_machine_mqtt.py
File metadata and controls
51 lines (40 loc) · 1.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import paho.mqtt.client as mqtt
import time
import json
from enum import Enum, auto
class State(Enum):
IDLE = auto()
RUNNING = auto()
PAUSED = auto()
STOPPED = auto()
ERROR = auto()
MAINTENANCE = auto()
class Vehicle:
def __init__(self):
self.state = State.IDLE
car = Vehicle()
def on_message(client, userdata, msg):
payload = msg.payload.decode()
print(f"Received message: {msg.topic} -> {payload}")
payload_dict = json.loads(payload)
event = payload_dict.get("value")
if event is None:
print("Value not provided in message")
return
try:
vehicle_state = State[event]
car.state = vehicle_state
print(car.state)
except KeyError:
print(f"Invalid state: {event}")
topic = "paho/temperature"
mqttc = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
mqttc.on_message = on_message
mqttc.exit_flag = False
mqttc.connect("localhost", 1883, 60)
mqttc.subscribe(topic)
mqttc.loop_start()
while car.state != State.STOPPED:
time.sleep(5)
mqttc.loop_stop()
mqttc.disconnect()