2 #include <ESP8266WiFi.h>
4 #include <Adafruit_NeoPixel.h>
9 #include "tag_handler.h"
12 MFRC522 mfrc522(SS_PIN, RST_PIN);
14 Adafruit_NeoPixel led = Adafruit_NeoPixel(9, LED_PIN, NEO_GRB + NEO_KHZ800);
16 // when did we last try to connect to wifi
17 unsigned long last_try = 0;
19 // is the wifi up and connected
22 if (WiFi.status() == WL_CONNECTED) return true;
26 // try and connect us, but give up after a while
33 if (WiFi.status() == WL_CONNECTED) return true;
36 Serial.print(F("WiFi Connecting to "));
37 Serial.println(WIFI_SSID);
39 WiFi.begin(WIFI_SSID, WIFI_PASS);
40 while (WiFi.status() != WL_CONNECTED && count < WIFI_COUNT) {
42 led.setPixelColor(0, 0, 0, pulse);
45 if (pulse <= 0 || pulse >= 192) rate=-rate;
49 if (WiFi.status() == WL_CONNECTED) {
50 Serial.print(F("Connected. IP="));
51 Serial.println(WiFi.localIP());
54 Serial.println(F("Wifi connect failed."));
58 // unrecoverable error state
65 led.setPixelColor(0, pulse, 0, 0);
68 if (pulse <= 0 || pulse >= 256) rate=-rate;
74 // Lock is idle, colour indicates online or not
75 void led_status(bool has_wifi)
77 // must be neatly divisible to work
78 static int pulse = 32;
82 led.setPixelColor(0, pulse, pulse, pulse);
84 led.setPixelColor(0, pulse, pulse, 0);
89 if (pulse == 0 || pulse == 32) rate=-rate;
96 Serial.println(F("\n\nRFID Doorlock. v1"));
98 pinMode(LOCK_PIN, OUTPUT);
99 digitalWrite(LOCK_PIN, LOW);
101 // Enable and clear LEDs
102 pinMode(LED_PIN, OUTPUT);
104 led.setBrightness(64);
107 // Test comms with the RFID board
109 byte v = mfrc522.PCD_ReadRegister(mfrc522.VersionReg);
112 Serial.println(F("RFID Init failed"));
115 Serial.print(F("MFRC Rev 0x"));
116 Serial.println(v, HEX);
118 // connect and indicate
119 led_status( wifi_connect() );
122 // check if we have a keyfile
125 if (SPIFFS.exists(KEYS_FILE)) {
126 Serial.print(F("Found keys file "));
127 Serial.println(KEYS_FILE);
129 Serial.print(F("Keys file "));
130 Serial.print(KEYS_FILE);
131 Serial.println(F(" not found"));
140 led.setPixelColor(0, 0, 255, 0);
142 digitalWrite(LOCK_PIN, HIGH);
144 digitalWrite(LOCK_PIN, LOW);
145 led.setPixelColor(0, 0, 0, 0);
151 led.setPixelColor(0, 255, 0, 0);
154 led.setPixelColor(0, 0, 0, 0);
162 bool success = false;
165 while (uid_fetch(mfrc522, uid, count)) {
166 Serial.print("Card: ");
167 Serial.print(uid_print(uid));
169 if (uid_valid(uid)) {
170 Serial.println(" MATCH");
174 Serial.println(" FAILED");
178 // wifi is up, report it
179 if (wifi_connected()) {
180 log_attempt(uid_print(uid), success);
184 led_status( wifi_connected() );
186 // wifi isnt connected, time to try again ?
187 if (!wifi_connected()) {
188 unsigned int now = millis();
189 if ( last_try + WIFI_RETRY < now) {
190 Serial.print("now="); Serial.print(now);
191 Serial.print(" last="); Serial.print(last_try);
192 Serial.print(" then="); Serial.println(last_try + WIFI_RETRY);
193 led_status( wifi_connect() );
198 // dont spin too fast