-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathRFID_Wiegand_MQTT.ino
535 lines (493 loc) · 14.4 KB
/
RFID_Wiegand_MQTT.ino
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
// Wiegand RFID access control reader
// Repo: https://github.com/nygma2004/RFID_Wiegand_MQTT
// author: Csongor Varga, csongor.varga@gmail.com
//
// Libraries:
// - Wiegand library: https://github.com/monkeyboard/Wiegand-Protocol-Library-for-Arduino
// - FastLED by Daniel Garcia
// - ArduinoJson: install latest from version 5
// Hardware:
// RFID reader: https://www.aliexpress.com/item/4001034161299.html
// ibutton reader: https://www.aliexpress.com/item/33002684974.html
// ibutton keys: https://www.aliexpress.com/item/33047420890.html
//
// NodeMCU pinout:
// D6: green wire of the reader
// D7: white wire of the reader
// GND: black wire of the reader
// 5V: 5V of the neopixel
// GND: GND of the neopixel
// D5: DataIn of the neopixel
// D2: ibutton
// D0: relay1
// D1: relay2
// D2: relay3
// D3: relay4
// A0: input switch
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <PubSubClient.h> // MQTT support
#include <Wiegand.h>
#include <OneWire.h>
#include "globals.h"
#include "settings.h"
#include <FastLED.h>
#include <ArduinoJson.h>
WIEGAND wg;
MDNSResponder mdns;
ESP8266WebServer server(80);
WiFiClient espClient;
PubSubClient mqtt(mqtt_server, 1883, 0, espClient);
CRGB leds[NUM_LEDS];
OneWire ibutton(IBUTTONPIN); // iButton connected on D2.
void setup() {
Serial.begin(115200);
Serial.println();
Serial.println("Wiegand RFID reader");
// Initiate the relay outputs
digitalWrite(RELAY1, HIGH);
pinMode(RELAY1, OUTPUT);
digitalWrite(RELAY2, HIGH);
pinMode(RELAY2, OUTPUT);
digitalWrite(RELAY3, HIGH);
pinMode(RELAY3, OUTPUT);
digitalWrite(RELAY4, HIGH);
pinMode(RELAY4, OUTPUT);
FastLED.addLeds<LED_TYPE, LED_PIN, COLOR_ORDER>(leds, NUM_LEDS).setCorrection( TypicalSMD5050 );
FastLED.setBrightness( BRIGHTNESS );
leds[0] = CRGB::Gold;
FastLED.show();
// Setting up wifi connection
Serial.print(F("Connecting to Wifi"));
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
seconds = 0;
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(F("."));
seconds++;
if (seconds % 2 == 0) {
leds[0] = CRGB::Red;
} else {
leds[0] = CRGB::Black;
}
FastLED.show();
if (seconds>180) {
// reboot the ESP if cannot connect to wifi
ESP.restart();
}
}
leds[0] = CRGB::Black;
FastLED.show();
Serial.println("");
Serial.print(F("Connected to "));
Serial.println(ssid);
Serial.print(F("IP address: "));
Serial.println(WiFi.localIP());
Serial.print(F("Signal [RSSI]: "));
Serial.println(WiFi.RSSI());
// Set up the MDNS and the HTTP server
if (mdns.begin("rfidmqtt", WiFi.localIP())) {
Serial.println(F("MDNS responder started"));
}
server.on("/", [](){ // Dummy page
server.send(200, "text/plain", "RFID MQTT");
});
server.begin();
Serial.println(F("HTTP server started"));
// Set up the MQTT server connection
if (mqtt_server!="") {
mqtt.setServer(mqtt_server, 1883);
mqtt.setCallback(MQTTcallback);
reconnect();
}
// default Wiegand Pin 2 and Pin 3 see image on README.md
// for non UNO board, use wg.begin(pinD0, pinD1) where pinD0 and pinD1
// are the pins connected to D0 and D1 of wiegand reader respectively.
wg.begin(WG_PIN_GREEN,WG_PIN_WHITE); // D6 D7 pins used on NodeMCU
}
void loop() {
// Handle MQTT connection/reconnection
if (mqtt_server!="") {
if (!mqtt.connected()) {
reconnect();
}
mqtt.loop();
delay(10);
}
handleWiegand();
handleiButton();
handleAnalogInput();
handleMQTTStatus();
handleStatusLED();
handlePulseReset();
}
// Check the analog input and post changes to MQTT
void handleAnalogInput() {
if (millis()-lastAnalog>ANALOGRATE) {
int sensorValue = analogRead(ANALOGINPUT);
bool sensorBool = (sensorValue>500 ? false : true);
if (lastAnalogState!=sensorBool) {
if (sensorBool) {
mqtt.publish(topicInput, "1");
} else {
mqtt.publish(topicInput, "0");
}
lastAnalogState = sensorBool;
lastAnalog=millis();
Serial.print("Input: ");
Serial.print(sensorBool);
Serial.println(" -> MQTT sent");
}
}
}
// Check devices connected to the iButton onewire interface
// and post the device ID in hex to MQTT
void handleiButton() {
const char * hex = "0123456789abcdef";
String code = "";
// Search for an iButton and assign the value to the buffer if found.
if (!ibutton.search (buffer)){
ibutton.reset_search();
return;
}
// At this point an iButton is found
for (int x = 0; x<8; x++){
code+= hex[(buffer[x]>>4) & 0xF];
code+= hex[ buffer[x] & 0xF];
}
//Serial.println(code);
// Check if this is a iButton
if ( buffer[0] != 0x01) {
Serial.println("Device is not a iButton");
return;
} else {
//Serial.println("Device is a iButton");
}
if ( ibutton.crc8( buffer, 7) != buffer[7]) {
Serial.println("CRC is not valid!");
return;
}
// check if it is not a duplicate scan
if ((code == lastiButton)&&(millis()-lastiButtonTime<IBUTTONLIMIT)) {
return;
}
lastiButton=code;
lastiButtonTime=millis();
Serial.print("iButton: ");
Serial.print(code);
String msg;
msg = "{\"code\":\"";
msg += code;
msg += "\",\"type\": \"ibutton\"}";
ibuttoncount++;
mqtt.publish(topicEvent, msg.c_str());
Serial.println(" -> MQTT sent");
}
// Handle the blink effect on the NeoPixel
void handleStatusLED() {
if (LEDphase!=0) {
// Phase 2, first color is on
if (LEDphase == 2) {
if (millis() - lastPhaseChange > LEDblink1) {
if (millis() - cycleStart < LEDduration) {
// move to the next phase
lastPhaseChange = millis();
SetLEDColor(LEDcolor2);
LEDphase = 3;
} else {
// duration expired, turn off the led
SetLEDColor("black");
LEDphase = 0;
}
}
}
// Phase 3, second color is on
if (LEDphase == 3) {
if (millis() - lastPhaseChange > LEDblink2) {
if (millis() - cycleStart < LEDduration) {
// move to the next phase
lastPhaseChange = millis();
SetLEDColor(LEDcolor1);
LEDphase = 2;
} else {
// duration expired, turn off the led
SetLEDColor("black");
LEDphase = 0;
}
}
}
// Phase 1, starting a new pattern
if (LEDphase == 1) {
lastPhaseChange = millis();
cycleStart = millis();
SetLEDColor(LEDcolor1);
LEDphase = 2;
}
}
}
// This resets the relay output when it was turned on in pulse mode
void handlePulseReset() {
if ((pulse1State)&&(millis()-lastPulse1>250)) {
digitalWrite(RELAY1, HIGH);
pulse1State = false;
Serial.println("Relay1 Pulse End");
}
if ((pulse2State)&&(millis()-lastPulse2>250)) {
digitalWrite(RELAY2, HIGH);
pulse2State = false;
Serial.println("Relay2 Pulse End");
}
}
// Color conversion routine
void SetLEDColor(String color) {
if (color=="black") {
leds[0] = CRGB::Black;
}
if (color=="yellow") {
leds[0] = CRGB::Yellow;
}
if (color=="red") {
leds[0] = CRGB::Red;
}
if (color=="green") {
leds[0] = CRGB::Green;
}
if (color=="blue") {
leds[0] = CRGB::Blue;
}
FastLED.show();
}
// Check the Wiegand input for new keypresses or scanned RFID tags
void handleWiegand() {
if (millis()-lastKey > PINTIMEOUT) {
if (pin!="") {
pin="";
lastKey=millis();
Serial.println("Pin timeout");
}
}
if(wg.available()) {
unsigned long wcode = wg.getCode();
int wtype = wg.getWiegandType();
Serial.print("Wiegand HEX = ");
Serial.print(wcode,HEX);
Serial.print(", DECIMAL = ");
Serial.print(wcode);
Serial.print(", Type W");
Serial.print(wtype);
// RFID card was scanned
if ((wtype==26)||(wtype==34)) {
String msg;
msg = "{\"code\":";
msg += wcode;
msg += ",\"type\": \"rfid\"}";
if (millis()-lastRfid > RFIDLIMIT) {
rfidcount++;
mqtt.publish(topicEvent, msg.c_str());
Serial.print(" -> MQTT sent");
lastRfid = millis();
} else {
mqtt.publish(topicEvent, "{ \"type\": \"rfidratelimit\" }");
Serial.print(" -> RATELIMITED");
}
}
// Keypad was used
if (wtype==4) {
if (wcode==27) {
pin+="*";
lastKey = millis();
Serial.print(" | PIN = ");
Serial.print(pin);
}
if (wcode==13) {
lastKey = millis();
String msg;
msg = "{\"code\": \"";
msg += pin;
msg += "\" ,\"type\": \"pin\"}";
Serial.print(" | PIN = ");
Serial.print(pin);
if (millis()-lastPin > PINLIMIT) {
pincount++;
mqtt.publish(topicEvent, msg.c_str());
Serial.print(" -> MQTT sent");
pin="";
lastPin = millis();
} else {
mqtt.publish(topicEvent, "{ \"type\": \"pinratelimit\" }");
Serial.print(" -> RATELIMITED");
pin="";
}
}
if ((wcode>=0)&&(wcode<=9)) {
pin+=wcode;
lastKey = millis();
Serial.print(" | PIN = ");
Serial.print(pin);
}
}
Serial.println();
}
}
// Send status messge over MQTT
void handleMQTTStatus() {
if (millis() - lastStatus >= STATUSUPDATEFRQ) {
lastStatus = millis();
String mqttStat;
mqttStat = "{\"rssi\":";
mqttStat += WiFi.RSSI();
mqttStat += ",\"uptime\":";
mqttStat += millis()/1000/60;
mqttStat += ",\"rfidcount\":";
mqttStat += rfidcount;
mqttStat += ",\"pincount\":";
mqttStat += pincount;
mqttStat += ",\"ibuttoncount\":";
mqttStat += ibuttoncount;
mqttStat += "}";
mqtt.publish(topicStatus, mqttStat.c_str());
Serial.print(F("Status: "));
Serial.println(mqttStat);
}
}
// MQTT reconnect logic
void reconnect() {
// Loop until we're reconnected
while (!mqtt.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (mqtt.connect(clientID, mqtt_user, mqtt_password)) {
Serial.println(F("connected"));
// ... and resubscribe
mqtt.subscribe(topicRelay1);
Serial.print(F("Subscribed to "));
Serial.println(topicRelay1);
mqtt.subscribe(topicRelay2);
Serial.print(F("Subscribed to "));
Serial.println(topicRelay2);
mqtt.subscribe(topicRelay3);
Serial.print(F("Subscribed to "));
Serial.println(topicRelay3);
mqtt.subscribe(topicRelay4);
Serial.print(F("Subscribed to "));
Serial.println(topicRelay4);
mqtt.subscribe(topicLight);
Serial.print(F("Subscribed to "));
Serial.println(topicLight);
mqtt.subscribe(topicPulse1);
Serial.print(F("Subscribed to "));
Serial.println(topicPulse1);
mqtt.subscribe(topicPulse2);
Serial.print(F("Subscribed to "));
Serial.println(topicPulse2);
} else {
Serial.print(F("failed, rc="));
Serial.print(mqtt.state());
Serial.println(F(" try again in 5 seconds"));
// Wait 5 seconds before retrying
delay(1000);
}
}
}
// MQTT callback function
void MQTTcallback(char* topic, byte* payload, unsigned int length) {
// Convert the incoming byte array to a string
char inData[120];
Serial.print("array: ");
for(int i = 0; i<length; i++){
//Serial.print((char)payload[i]);Serial.print("_");
inData[i] = (char)payload[i];
}
//Serial.println();
String strTopic = String((char*)topic);
payload[length] = '\0'; // Null terminator used to terminate the char array
String message = (char*)payload;
Serial.print(F("Message arrived on topic: ["));
Serial.print(strTopic);
Serial.print(F("], "));
Serial.println(message);
if (strTopic==(String)topicRelay1) {
int newvalue = atoi((char *)payload);
if (newvalue==0) {
digitalWrite(RELAY1, HIGH);
Serial.println("Relay1 off");
}
if (newvalue==1) {
digitalWrite(RELAY1, LOW);
Serial.println("Relay1 on");
}
}
if (strTopic==(String)topicRelay2) {
int newvalue = atoi((char *)payload);
if (newvalue==0) {
digitalWrite(RELAY2, HIGH);
Serial.println("Relay2 off");
}
if (newvalue==1) {
digitalWrite(RELAY2, LOW);
Serial.println("Relay2 on");
}
}
if (strTopic==(String)topicRelay3) {
int newvalue = atoi((char *)payload);
if (newvalue==0) {
digitalWrite(RELAY3, HIGH);
Serial.println("Relay3 off");
}
if (newvalue==1) {
digitalWrite(RELAY3, LOW);
Serial.println("Relay3 on");
}
}
if (strTopic==(String)topicRelay4) {
int newvalue = atoi((char *)payload);
if (newvalue==0) {
digitalWrite(RELAY4, HIGH);
Serial.println("Relay4 off");
}
if (newvalue==1) {
digitalWrite(RELAY4, LOW);
Serial.println("Relay4 on");
}
}
if (strTopic==(String)topicPulse1) {
int newvalue = atoi((char *)payload);
if (newvalue==1) {
digitalWrite(RELAY1, LOW);
Serial.println("Relay1 Pulse");
lastPulse1 = millis();
pulse1State = true;
}
}
if (strTopic==(String)topicPulse2) {
int newvalue = atoi((char *)payload);
if (newvalue==1) {
digitalWrite(RELAY2, LOW);
Serial.println("Relay2 Pulse");
lastPulse2 = millis();
pulse2State = true;
}
}
if (strTopic==(String)topicLight) {
StaticJsonBuffer<200> jsonBuffer;
JsonObject& root = jsonBuffer.parseObject(inData);
LEDcolor1 = root["color1"].as<String>();
Serial.print("Color1 = ");
Serial.print(LEDcolor1);
LEDcolor2 = root["color2"].as<String>();
Serial.print(", Color2 = ");
Serial.print(LEDcolor2);
LEDblink1 = root["blink1"];
Serial.print(", Blink1 = ");
Serial.print(LEDblink1);
LEDblink2 = root["blink2"];
Serial.print(", Blink2 = ");
Serial.print(LEDblink2);
LEDduration = root["duration"];
Serial.print(", Duration = ");
Serial.println(LEDduration);
LEDphase = 1;
}
}