|
| 1 | +import json |
| 2 | +import paho.mqtt.client as mqtt |
| 3 | +from datetime import datetime, timedelta |
| 4 | + |
| 5 | + |
| 6 | +def on_connect(client, user_data, flags, reason_code, properties): |
| 7 | + print(f"Connected with result code {reason_code}") |
| 8 | + # Subscribing in on_connect() means that if we lose the connection and |
| 9 | + # reconnect then subscriptions will be renewed. |
| 10 | + client.subscribe("purdue-dac/carrot") |
| 11 | + |
| 12 | + |
| 13 | +# The callback for when a PUBLISH message is received from the server. |
| 14 | +def on_message(client, user_data, msg): |
| 15 | + uid = msg.payload.hex().upper() |
| 16 | + with open("rfid.json", "r") as fp: |
| 17 | + tags = json.load(fp) |
| 18 | + tags[uid] = 5 |
| 19 | + with open("rfid.json", "w") as fp: |
| 20 | + json.dump(tags, fp) |
| 21 | + print(uid) |
| 22 | + global last_time # Bad practice. Only use in emergency |
| 23 | + if last_time is None: |
| 24 | + last_time = datetime.now() |
| 25 | + if (datetime.now() - last_time) < timedelta(seconds=4, microseconds=500): |
| 26 | + client.publish("purdue-dac/sound", "1") |
| 27 | + elif (datetime.now() - last_time) > timedelta(seconds=7): |
| 28 | + last_time = None |
| 29 | + else: |
| 30 | + client.publish("purdue-dac/sound", "2") |
| 31 | + last_time = None |
| 32 | + |
| 33 | + |
| 34 | +client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2) |
| 35 | +client.on_connect = on_connect |
| 36 | +client.on_message = on_message |
| 37 | +last_time = None |
| 38 | + |
| 39 | +client.connect("localhost", 1883, 60) |
| 40 | + |
| 41 | +# Blocking call that processes network traffic, dispatches callbacks and |
| 42 | +# handles reconnecting. |
| 43 | +# Other loop*() functions are available that give a threaded interface and a |
| 44 | +# manual interface. |
| 45 | +client.loop_forever() |
0 commit comments