-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient_mqtt.py
81 lines (63 loc) · 2.14 KB
/
client_mqtt.py
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# coding=utf-8
import paho.mqtt.client as mqtt
import RPi.GPIO as GPIO
import MFRC522
import signal
STATUS_TOPIC = 'rc522/01/status'
EVENT_TOPIC = 'rc522/01'
HOST = "localhost"
PORT = 1883
continue_reading = True
# Capture SIGINT for cleanup when the script is aborted
def end_read(signal, frame):
global continue_reading
print("Ctrl+C captured, ending read.")
continue_reading = False
GPIO.cleanup()
def mqtt_on_message(client, userdata, msg):
print(msg.topic + " " + str(msg.payload))
try:
controller_name, reader_code, card = msg.topic.split('/')
if 'granted' in msg:
print ('granted for card %s' % card )
except:
pass
def mqtt_init():
client_id = 'rc522'
client = mqtt.Client()
client.on_message = mqtt_on_message
return client
def main():
global continue_reading
continue_reading = True
client = mqtt_init()
client.connect("192.168.0.3", 1883, 60)
client.loop_start()
print("RFID is ready")
client.publish(STATUS_TOPIC, "rc522 is online", qos=1, retain=True)
MIFAREReader = MFRC522.MFRC522()
# This loop keeps checking for chips. If one is near it will get the UID and authenticate
while continue_reading:
try:
# Scan for cards
(status, TagType) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL)
# If a card is found
if status == MIFAREReader.MI_OK:
print("Card detected")
# Get the UID of the card
(status, uid) = MIFAREReader.MFRC522_Anticoll()
# If we have the UID, continue
if status == MIFAREReader.MI_OK:
card = " ".join(["{:02x}".format(x) for x in uid])
print("Card read UID: %s " % card)
client.publish(EVENT_TOPIC, '{"card_code":"%s"}' % card )
client.subscribe(EVENT_TOPIC+'/'+card)
except KeyboardInterrupt:
print("End")
continue_reading = False
client.publish(STATUS_TOPIC, "rc522 dead", qos=1, retain=True)
client.loop_stop()
client.disconnect()
GPIO.cleanup()
if __name__ == "__main__":
main()