· 5 years ago · Jan 28, 2021, 09:14 AM
1#include <ESP8266FtpServer.h> //libreria server FTP https://github.com/nailbuster/esp8266FTPServer
2#include <FS.h> //libreria per leggere file da SPIFFS
3#include <ESP8266WiFi.h>
4#include <ESP8266mDNS.h>
5#include <ESP8266HTTPClient.h>
6#include <WiFiUdp.h>
7#include <ArduinoOTA.h>
8#include <RCSwitch.h>
9
10#define door_pin 3 //pin contatto chiave
11#define D2 4 //PIN reading signal on GPIO4
12
13/* Inizializzo istanza RCSwitch */
14RCSwitch mySwitch = RCSwitch();
15
16/* Definizione parametri di rete */
17#define HOST "nomehost"
18#ifndef STASSID
19#define STASSID "Nomerete"
20#define STAPSK "password"
21#endif
22
23FtpServer ftpSrv; //set #define FTP_DEBUG in ESP8266FtpServer.h to see ftp verbose on serial
24
25/* Variabili globali*/
26const char* ssid = STASSID;
27const char* password = STAPSK;
28
29const byte string_size = 7; //lunghezza stringa chiave
30String chiave; //dichiara la chiave "stringa"
31
32unsigned long log_delay = 0;
33
34void setup() {
35 Serial.begin(115200);
36 pinMode(LED_BUILTIN,OUTPUT);
37 digitalWrite(LED_BUILTIN,HIGH);
38 mySwitch.enableReceive(D2); // Receiver on interrupt 0 => that is pin #2
39
40 //Serial.println("Booting");
41 WiFi.mode(WIFI_STA);
42 WiFi.begin(ssid, password);
43 //Serial.println("Waiting for first connection..."); //this need to jump?
44 IPAddress ip(192,168,1,32);
45 IPAddress gateway(192,168,1,1);
46 IPAddress subnet(255,255,255,0);
47 WiFi.config(ip, gateway, subnet);
48
49 while (WiFi.status() != WL_CONNECTED) { //
50 //Serial.print(".");
51 delay(500);
52 }
53 //Serial.println("\nConnected!");
54
55 if (SPIFFS.begin()) { //monta file system interno e configura server ftp
56 //Serial.println("SPIFFS opened!");
57 ftpSrv.begin("nomeFTP","PassFTP"); //username, password for ftp. set ports in ESP8266FtpServer.h (default 21, 50009 for PASV)
58 }else{
59 //Serial.println("ERROR with FTP or FileSystem");
60 }
61 //update_database(); //update database at boot
62
63 // Port defaults to 8266
64 // ArduinoOTA.setPort(8266);
65
66 // Hostname defaults to esp8266-[ChipID]
67 ArduinoOTA.setHostname("Garage_manager");
68
69 // No authentication by default
70 //ArduinoOTA.setPassword("admin"); //CHANGE ME!!!
71
72 // Password can be set with it's md5 value as well
73 // MD5(admin) = 21232f297a57a5a743894a0e4a801fc3
74 ArduinoOTA.setPasswordHash("aaaaash quello di pikachu");
75
76 ArduinoOTA.onStart([]() {
77 String type;
78 if (ArduinoOTA.getCommand() == U_FLASH) {
79 type = "sketch";
80 } else { // U_FS
81 type = "filesystem";
82 }
83 //SPIFFS.end(); // non sono sicuro che vada qui
84 // NOTE: if updating FS this would be the place to unmount FS using FS.end()
85 //Serial.println("Start updating " + type);
86 });
87// ArduinoOTA.onEnd([]() {
88// //Serial.println("\nEnd");
89// });
90// ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
91// //Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
92// });
93// ArduinoOTA.onError([](ota_error_t error) {
94// //Serial.printf("Error[%u]: ", error);
95// if (error == OTA_AUTH_ERROR) {
96// //Serial.println("Auth Failed");
97// } else if (error == OTA_BEGIN_ERROR) {
98// //Serial.println("Begin Failed");
99// } else if (error == OTA_CONNECT_ERROR) {
100// //Serial.println("Connect Failed");
101// } else if (error == OTA_RECEIVE_ERROR) {
102// //Serial.println("Receive Failed");
103// } else if (error == OTA_END_ERROR) {
104// //Serial.println("End Failed");
105// }
106// });
107
108 ArduinoOTA.begin();
109// Serial.println("Ready");
110// Serial.print("IP address: ");
111// Serial.println(WiFi.localIP());
112 send_log(String("REBOOT")); //Send reboot log
113 update_database();
114}
115
116void loop() {
117 ftpSrv.handleFTP(); //this run FTP server
118 ArduinoOTA.handle(); //this checks for OTA
119 remote_check(); //controlla se inserita una chiave, ne legge il codice e la converte in stringa
120 //send_log(); //invia log di tentata apertura (a prescindere dall'esito)
121}
122
123
124int remote_check() {
125 if (mySwitch.available()){
126 if (mySwitch.getReceivedBitlength() == 24){
127 chiave = mySwitch.getReceivedValue();
128 }
129 else {
130 mySwitch.resetAvailable();
131 return 0;
132 }
133 }
134 else {
135 return 0; //return if no remote detected
136 }
137 if (chiave.length() == string_size){
138 /* -- Read from database -- */
139 File key_file = SPIFFS.open("/keys.txt","r");
140 if (!key_file){
141 open_door(); //open the door anyway and send key log
142 ESP.restart();
143 }
144
145 bool key_found = 0;
146 uint8_t k;
147 bool error_found;
148 String test_key;
149 while (key_file.available() && !key_found) { // esegui finchè non finisce il file o non trovi la chiave
150 test_key = key_file.readStringUntil('\n'); //legge
151 k = 0;
152 key_found = 1; // assume we found the key!
153 error_found = 0;
154 while ( (k < string_size) && !error_found) {
155 if ( chiave[k] != test_key[k] ){ // IF a != b then false, because: one fails, all fail
156 key_found = 0; //reset the assumption if we got an error, so we can restart the cycle on the next line
157 error_found = 1; //stop the cycle for scanning this key and jump on the next one
158 }
159 k++; //increment counter
160 }
161 }
162 key_file.close();
163 if(key_found){
164 open_door(); //finally open the door
165 }
166 else{
167 wrong_code();
168 }
169 return 1; //return 1 if key detected
170 }
171 else{
172 mySwitch.resetAvailable();
173 }
174}
175
176void send_log(String chiave){
177 if (WiFi.status() == WL_CONNECTED){
178 HTTPClient http;
179 String postData = "api_key=bzzzocchioalleAPI&KEY=" + chiave; //costruisci stringa POST
180 //Serial.println(postData); // should be something as api_key=bzzzzzAPII&KEY=44 44 55 66
181 http.begin("http://192.168.1.185:5049/php/post-esp-data.php");
182 http.addHeader("Content-Type", "application/x-www-form-urlencoded");
183 int httpCode = http.POST(postData);
184 // if (httpCode>0) {
185 // Serial.print("HTTP Response code: ");
186 // Serial.println(httpCode);
187 // if (httpCode == 200){
188 // Serial.println("Chiave inviata correttamente");
189 // }
190 // }
191// else {
192// Serial.print("Error code: ");
193// Serial.println(httpCode);
194// }
195 http.end();
196 }
197}
198
199
200void open_door(){
201 digitalWrite(door_pin,LOW); //simula chiusura contatto, da rivedere!!
202// Serial.println("Chiave autorizzata");
203 digitalWrite(LED_BUILTIN,LOW);
204 delay(500);
205 digitalWrite(door_pin,HIGH);
206 digitalWrite(LED_BUILTIN,HIGH);
207 delay(5000);
208 mySwitch.resetAvailable();
209 if(millis()-log_delay > 10000){
210 log_delay = millis();
211 send_log(chiave);
212 }
213}
214void wrong_code(){
215 for (int i=0; i<3; i++){
216 digitalWrite(LED_BUILTIN,LOW);
217 delay(50);
218 digitalWrite(LED_BUILTIN,HIGH);
219 delay(50);
220 }
221// Serial.println("Chiave NON autorizzata");
222 mySwitch.resetAvailable();
223 if(millis()-log_delay > 10000){
224 log_delay = millis();
225 send_log(chiave);
226 }
227}
228
229void update_database(){
230 if (WiFi.status() == WL_CONNECTED){
231 WiFiClient client;
232 HTTPClient http;
233// Serial.println("Updating db..");
234 String url = String("http://192.168.1.185:5049/php/keys.txt");
235 String file_name="/keys.txt";
236 File f = SPIFFS.open(file_name, "w");
237 if (f) {
238 http.begin(client,url);
239 int httpCode = http.GET();
240 if (httpCode > 0) {
241 if (httpCode == HTTP_CODE_OK) {
242 // Serial.println("Http ok");
243 int len = http.getSize();
244 uint8_t buff[128] = { 0 };
245#if 0
246 // with API
247 f.println(http.getString());
248#else
249 // get tcp stream
250 WiFiClient * stream = &client;
251 // read all data from server
252 while (http.connected() && (len > 0 || len == -1)) {
253 // read up to 128 byte
254 int c = stream->readBytes(buff, std::min((size_t)len, sizeof(buff)));
255 // Serial.printf("readBytes: %d\n", c);
256// if (!c) {
257// Serial.println("read timeout");
258// }
259 // write it to file
260 f.write(buff, c);
261 if (len > 0) {
262 len -= c;
263 }
264 }
265#endif
266 }
267 }// else {
268 // Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
269 // }
270 f.close();
271 }
272 http.end();
273 }
274}