From 975931fb24bc92607c2fdfd5b6afbaf167849886 Mon Sep 17 00:00:00 2001 From: Arif Date: Tue, 23 Jun 2020 19:10:21 +0700 Subject: [PATCH] new version 1.4.0 --- .vscode/settings.json | 35 +- README.md | 159 ++--- .../AuthWithPassword/AuthWithPassword.ino | 86 +++ examples/ReadCard/ReadCard.ino | 8 +- .../RegisterIDCard.ino} | 3 +- .../Simple.ino} | 19 +- .../UserConfirmationParameters.ino | 96 +++ library.json | 2 +- library.properties | 2 +- platformio.ini | 22 +- src/Spacecat.cpp | 612 ++++++++++++------ src/Spacecat.h | 200 ++++-- 12 files changed, 880 insertions(+), 364 deletions(-) create mode 100644 examples/AuthWithPassword/AuthWithPassword.ino rename examples/{LiveRegister/LiveRegister.ino => RegisterIDCard/RegisterIDCard.ino} (96%) rename examples/{SimpleValidation/SimpleValidation.ino => Simple/Simple.ino} (81%) create mode 100644 examples/UserConfirmationParameters/UserConfirmationParameters.ino diff --git a/.vscode/settings.json b/.vscode/settings.json index 319fe94..e54e9d1 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,12 +1,12 @@ { "git.ignoreLimitWarning": true, - "editor.fontFamily": "Operator Mono", + "editor.fontFamily": "Fira Code", "editor.fontLigatures": true, "editor.cursorStyle": "line-thin", "editor.cursorBlinking": "smooth", "workbench.fontAliasing": "auto", - "editor.fontSize": 15, + "editor.fontSize": 13.5, "editor.smoothScrolling": true, "editor.tabSize": 2, "window.zoomLevel": 0, @@ -24,6 +24,33 @@ "unordered_map": "cpp", "vector": "cpp", "initializer_list": "cpp", - "functional": "cpp" - } + "functional": "cpp", + "atomic": "cpp", + "cctype": "cpp", + "clocale": "cpp", + "cmath": "cpp", + "cstdarg": "cpp", + "cstdint": "cpp", + "cstdio": "cpp", + "cstdlib": "cpp", + "cwchar": "cpp", + "cwctype": "cpp", + "exception": "cpp", + "fstream": "cpp", + "iosfwd": "cpp", + "istream": "cpp", + "limits": "cpp", + "new": "cpp", + "ostream": "cpp", + "numeric": "cpp", + "sstream": "cpp", + "stdexcept": "cpp", + "streambuf": "cpp", + "cinttypes": "cpp", + "tuple": "cpp", + "type_traits": "cpp", + "utility": "cpp", + "typeinfo": "cpp" + }, + "editor.fontWeight": "600" } \ No newline at end of file diff --git a/README.md b/README.md index 58bc15c..247522e 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,8 @@ With this library you can easily manage the users with RFID card data stored in Youtube Videos (Bahasa) [here](https://youtu.be/dyNRkAb60So) +Youtube Videos (English) *Soon* + ## Hardware Requirements >Spacecat is primary built for ESP8266 Chip. but for now ESP32 is a bit of a problem, now still in progress :) - Any board with ESP8266/ESP32 chips (Wemos, NodeMCU board, etc). @@ -41,83 +43,17 @@ Now grab the hardware and some jumper wire and connect it like image shown below ![](https://github.com/AsyaSyarif/RFID-Spacecat/blob/master/circuits/basic.PNG) #### Wiring -| ESP8266 | RC522 | -| ------------- |:-------------:| -| 3V3 | 3.3V | -| GND | GND | -| D8 (GPIO15) | SDA / SS | -| D5 (GPIO14) | SCK | -| D7 (GPIO13) | MOSI | -| D6 (GPIO12) | MISO | -| -| IRQ | -| GND / X | RST | - -### Simple Usage or Open this [Examples](https://github.com/AsyaSyarif/RFID-Spacecat/tree/master/examples) folder. -``` -#include "Spacecat.h" - -const char WIFI_SSID[] = ""; // your network SSID (name) -const char WIFI_PASSWORD[] = ""; // your network password - -const char DEVICE_NAME[] = ""; -const char SPACECAT_USERNAME[] = ""; -const char SPACECAT_PASSWORD[] = ""; - -#define RC522_SS_PIN 15 - -Spacecat cat(SPACECAT_USERNAME, SPACECAT_PASSWORD, DEVICE_NAME); - -void handleCallback(int code, String refrenceID, String name, String messages){ - Serial.print("Code : "); - Serial.println(code); - - Serial.print("Ref : "); - Serial.println(refrenceID); - - Serial.print("Name : "); - Serial.println(name); - - Serial.print("Messages : "); - Serial.println(messages); -} - - -void setup() { - //for debuging purpose - Serial.begin(115200); +|ESP32 | ESP8266 | RC522 | +| --- | ------------- |:-------------:| +| - | 3V3 | 3.3V | +| - | GND | GND | +| - | D8 (GPIO15) | SDA / SS | +| - | D5 (GPIO14) | SCK | +| - | D7 (GPIO13) | MOSI | +| - | D6 (GPIO12) | MISO | +| - | -| IRQ | +| - | GND / X | RST | - Serial.println(); - Serial.println(); - Serial.print("Connecting to "); - Serial.print(WIFI_SSID); - - WiFi.mode(WIFI_STA); - WiFi.begin(WIFI_SSID, WIFI_PASSWORD); - - while (WiFi.status() != WL_CONNECTED) { - delay(200); - Serial.print("."); - } - - Serial.println(""); - Serial.println("WiFi connected"); - Serial.print("IP address: "); - Serial.println(WiFi.localIP()); - - cat.begin(RC522_SS_PIN); - cat.setSimpleCallback(&handleCallback); -} - - -void loop() { - - if(WiFi.status() == WL_CONNECTED){ - cat.loop(); - } - -} - -``` ## Get The Authentication Key + **Please pay attention to accessing our website, please use desktop version instead mobile version [only temporary]** @@ -131,10 +67,11 @@ void loop() { const char SPACECAT_USERNAME[] = ""; const char SPACECAT_PASSWORD[] = ""; ``` - +## Usage + Please check [Example's](https://github.com/Asyasyarif/RFID-Spacecat/tree/master/examples) folder ## API Docs -Basically every we doing request to the server, that will return 4 basic data, which will be explained below +Basically every we doing request to the server that will return the data, which will be explained below | Value | Description | | ------------- | ------------- | @@ -148,26 +85,60 @@ Basically every we doing request to the server, that will return 4 basic data, w | | `` [109] `` Not found| | | `` [110] `` User parameter updated| | | `` [111] `` Password OK| -| **Reference** | ID Reference for every requests | -| **Name** | Name of user | -| **Messages** | Messages status from requests | - +| | `` [112] `` Password Confirmation| + +## Structures +We'll separate the code structures into 3 parts : `.user`, `.ruleParameter`, `.placementParameter` + +| Struct | Data | Data Type | Description | +| ------------- | ------------- | --------- | --------- | +| `{objectName}.user` | `.name` | `String` | Username | +| | `.rfid` | `String` | User RFID | +| | `.email` | `char` | Email | +| | `.isMaster` | `char` | `true` if user has set to Master | +| | `.messages` | `char` | Message of every request | +| | `.phoneNumber` | `char` | Phone Number | +| | `.amount` | `int` | Amount of default parameter | +| | `.referenceID` | `int` | Unique ID for every requests | +| | `.havePassword` | `bool` | If user have password that's will be `true` | +| | `.status` | `bool` | User status | +| | `.statusCode` | `uint16_t` | Return code | +|`{objectName}.ruleParameter` | `.amount` | `int` | Amount of rule parameter | +|`{objectName}.placementParameter` | `.Name1` | `char` | Name of Placement parameter 1 | +| | `.value1` | `int` | Amount of rule parameter 1| +| | `.Name2` | `char` | Name of Placement parameter 2 | +| | `.value2` | `int` | Amount of rule parameter 2| +| | `.Name3` | `char` | Name of Placement parameter 3 | +| | `.value3` | `int` | Amount of rule parameter 3| +| | `.Name4` | `char` | Name of Placement parameter 4 | +| | `.value4` | `int` | Amount of rule parameter 4| ## Functions -| Function | Description | Default | +| Function | Default | Description | | ------------- | ------------- | --------- | -| ``clear()`` | Clear data and proccess | - | -| ``readCard()`` | Just only reading RFID Card | - | -| ``registerID()`` | Registering the ID and added to waiting list | - | -| ``setDebug(bool debug)`` | Debugging purpose | ``true `` | | -| ``intervalReading(int time)`` | Delay for every reading the card| ``1000ms`` | -| ``begin(uint8_t SS_PIN)`` | Initialization RC522 Module SS Pin and Reset to GND| - | -| ``begin(uint8_t SS_PIN, uint8_t RESET_PIN)`` |Initialization RC522 Module SS Pin & Reset Pin | - | -| ``enteredPassword(String password)`` | User inserting password | - | -|`` Spacecat(String Username, String Password, String DeviceName)`` | Initialization your credentials | - | - +| ``cancel()`` | | Cancel data and proccess | +| ``confirm()`` | | Confirm for changes parameters | +| ``onlyReadingCard()`` | | Just only reading RFID Card | +| ``registerID()`` | | Registering the ID and added to waiting list | +| ``setDebug(bool debug)`` | ``true `` | Debugging purpose | +| ``setIntervalReading(int time)`` | ``1000ms`` | Delay for every reading the card +| `` setTimeoutPassword(int time)`` | ``10000ms`` | Timer for user inserting the password +| ``begin(uint8_t SS_PIN)`` | | Initialization RC522 Module SS Pin and Reset to GND | +| ``begin(uint8_t SS_PIN, uint8_t RESET_PIN)`` | | Initialization RC522 Module SS Pin & Reset Pin | +| ``enteredPassword(String password)`` | | User inserting password| +|`` Spacecat(String Username, String Password, String DeviceName)`` | | Initialization your credentials | +|`` setCallback(&handleCallback);`` | | Receive all the data feedback on any requests | + + + +## Contribute +There are several ways to contribute to Spacecat development. You can contribute to the repository by doing: +- Pull requests +- Create the issues ## To Do - Write clean code / Refactoring - Write API's -- Write Documentations \ No newline at end of file +- Write Documentations + + [just contact me if you had any questions](https://www.instagram.com/asya_syarif/) \ No newline at end of file diff --git a/examples/AuthWithPassword/AuthWithPassword.ino b/examples/AuthWithPassword/AuthWithPassword.ino new file mode 100644 index 0000000..e0b27b8 --- /dev/null +++ b/examples/AuthWithPassword/AuthWithPassword.ino @@ -0,0 +1,86 @@ + + /******************************************************************* + * + * Spacecat requires : + * RC522 : https://github.com/miguelbalboa/rfid + * ArduinoJson : https://github.com/bblanchon/ArduinoJson + * - im use the latest version (Currently is 6.14.1) + * + * Makes sure the user entered the password + * + * + * Written by Arif @2019. + * Bandung, Indonesia + * https://rfid.asyarif.net + * + *******************************************************************/ + + +#include "Spacecat.h" + +const char WIFI_SSID[] = ""; // your network SSID (name) +const char WIFI_PASSWORD[] = ""; // your network password + +const char DEVICE_NAME[] = ""; +const char SPACECAT_USERNAME[] = ""; +const char SPACECAT_PASSWORD[] = ""; + +#define RC522_SS_PIN 15 //D8 +Spacecat cat(SPACECAT_USERNAME, SPACECAT_PASSWORD, DEVICE_NAME); + +void handleCallback(bool userFound){ + + if(userFound){ + Serial.print("hello "); + Serial.println(cat.user.name); + Serial.println(cat.user.messages); + + /* + - Make sure the user have a password + - the password must be 6 digits and numeric + - In this case For example I'd with simple password and hard-coded "123456" + */ + if(cat.user.statusCode == FILL_THE_PASSWORD){ + if(cat.enteredPassword("123456")){ + Serial.println("The Password correct"); + }else{ + Serial.println("The Password incorrect"); + } + } + } + +} + + +void setup() { + //for debuging purpose + Serial.begin(115200); + + Serial.println(); + Serial.println(); + Serial.print("Connecting to "); + Serial.print(WIFI_SSID); + WiFi.begin(WIFI_SSID, WIFI_PASSWORD); + + while (WiFi.status() != WL_CONNECTED) { + delay(500); + Serial.print("."); + } + + Serial.println(""); + Serial.println("WiFi connected"); + Serial.print("IP address: "); + Serial.println(WiFi.localIP()); + + cat.setTimeoutPassword(5000); // 5 seconds + cat.begin(RC522_SS_PIN); + cat.setCallback(&handleCallback); +} + +void loop() { + + if(WiFi.status() == WL_CONNECTED){ + cat.loop(); + } + +} \ No newline at end of file diff --git a/examples/ReadCard/ReadCard.ino b/examples/ReadCard/ReadCard.ino index 1cc9f39..de5c3b6 100644 --- a/examples/ReadCard/ReadCard.ino +++ b/examples/ReadCard/ReadCard.ino @@ -13,7 +13,7 @@ #include "Spacecat.h" -#define RC522_SS_PIN 15 +#define RC522_SS_PIN 5 Spacecat cat; void setup(){ @@ -26,8 +26,12 @@ void setup(){ void loop(){ - cat.readCard(); + if(cat.onlyReadCard()){ + Serial.print("ID: "); + Serial.println(cat.user.rfid); + } delay (10); } + diff --git a/examples/LiveRegister/LiveRegister.ino b/examples/RegisterIDCard/RegisterIDCard.ino similarity index 96% rename from examples/LiveRegister/LiveRegister.ino rename to examples/RegisterIDCard/RegisterIDCard.ino index 9510a62..8afa8d2 100644 --- a/examples/LiveRegister/LiveRegister.ino +++ b/examples/RegisterIDCard/RegisterIDCard.ino @@ -6,7 +6,7 @@ * ArduinoJson : https://github.com/bblanchon/ArduinoJson * - im use the latest version (Currently is 6.14.1) * - * If you don't want to copy paste the ID card, + * If you don't want to copy an dpaste the ID card, * you can use this example and automatically the ID card will appear on your project * * Written by Arif @2019. @@ -29,7 +29,6 @@ const char SPACECAT_PASSWORD[] = ""; Spacecat cat(SPACECAT_USERNAME, SPACECAT_PASSWORD, DEVICE_NAME); - void setup() { //for debuging purpose Serial.begin(115200); diff --git a/examples/SimpleValidation/SimpleValidation.ino b/examples/Simple/Simple.ino similarity index 81% rename from examples/SimpleValidation/SimpleValidation.ino rename to examples/Simple/Simple.ino index 613f3ec..2b367f0 100644 --- a/examples/SimpleValidation/SimpleValidation.ino +++ b/examples/Simple/Simple.ino @@ -30,19 +30,16 @@ const char SPACECAT_PASSWORD[] = ""; Spacecat cat(SPACECAT_USERNAME, SPACECAT_PASSWORD, DEVICE_NAME); -void handleCallback(int code, String refrenceID, String name, String messages){ - Serial.print("Code : "); - Serial.println(code); +void handleCallback(bool userFound){ - Serial.print("Ref : "); - Serial.println(refrenceID); + if(userFound){ + Serial.print("Name : "); + Serial.println(cat.user.name); - Serial.print("Name : "); - Serial.println(name); - - Serial.print("Messages : "); - Serial.println(messages); + Serial.print("Messages : "); + Serial.println(cat.user.messages); + } } @@ -70,7 +67,7 @@ void setup() { Serial.println(WiFi.localIP()); cat.begin(RC522_SS_PIN); - cat.setSimpleCallback(&handleCallback); + cat.setCallback(&handleCallback); } diff --git a/examples/UserConfirmationParameters/UserConfirmationParameters.ino b/examples/UserConfirmationParameters/UserConfirmationParameters.ino new file mode 100644 index 0000000..ee199ef --- /dev/null +++ b/examples/UserConfirmationParameters/UserConfirmationParameters.ino @@ -0,0 +1,96 @@ + + /******************************************************************* + * + * Spacecat requires : + * RC522 : https://github.com/miguelbalboa/rfid + * ArduinoJson : https://github.com/bblanchon/ArduinoJson + * - im use the latest version (Currently is 6.14.1) + * + * An simple example of how to auth the User : + * you can very easily manage user, placement, and can also add the rule for each placement + * + * Every you doing tap card or request to server, You definitely get a return value : + * 101 Project not active + * 102 User not active + * 103 Placement not + * 104 SUCCEED + * 105 UNSUCCESSFULL + * 106 Invalid Password + * 107 User Need Fill the Password + * 108 User reach the limit of parameter + * 109 Not Found + * + * + * Written by Arif @2019. + * Bandung, Indonesia + * https://rfid.asyarif.net + * + *******************************************************************/ + + +#include "Spacecat.h" + +const char WIFI_SSID[] = ""; // your network SSID (name) +const char WIFI_PASSWORD[] = ""; // your network password + +const char DEVICE_NAME[] = ""; +const char SPACECAT_USERNAME[] = ""; +const char SPACECAT_PASSWORD[] = ""; + +#define RC522_SS_PIN 15 //D8 +Spacecat cat(SPACECAT_USERNAME, SPACECAT_PASSWORD, DEVICE_NAME); + +void handleCallback(bool userFound){ + + if(userFound){ + + Serial.print("hello "); + Serial.println(cat.user.name); + Serial.println(cat.user.messages); + + if(cat.user.statusCode == PARAM_CONFIRM){ + Serial.println("Confirm ? "); + if(cat.confirm()){ // Yes + Serial.println("Success updating parameter"); + }else{ + Serial.println("Failed updating parameter"); + } + } + } + +} + +void setup() { + //for debuging purpose + Serial.begin(115200); + + Serial.println(); + Serial.println(); + Serial.print("Connecting to "); + Serial.print(WIFI_SSID); + WiFi.begin(WIFI_SSID, WIFI_PASSWORD); + + while (WiFi.status() != WL_CONNECTED) { + delay(500); + Serial.print("."); + } + + cat.setIntervalReading(2000); // delay between reading the card by 2 seconds + Serial.println(""); + Serial.println("WiFi connected"); + Serial.print("IP address: "); + Serial.println(WiFi.localIP()); + + cat.setIntervalReading(2000); + cat.begin(RC522_SS_PIN); + cat.setCallback(&handleCallback); +} + + +void loop() { + + if(WiFi.status() == WL_CONNECTED){ + cat.loop(); + } + +} \ No newline at end of file diff --git a/library.json b/library.json index 416128c..337602f 100644 --- a/library.json +++ b/library.json @@ -7,7 +7,7 @@ "type": "git", "url": "https://github.com/AsyaSyarif/RFID-Spacecat" }, - "version": "1.3.1", + "version": "1.4.0", "exclude": "doc", "frameworks": "arduino", "platforms": ["espressif8266","espressif32"] diff --git a/library.properties b/library.properties index 5710d8c..701954d 100644 --- a/library.properties +++ b/library.properties @@ -1,5 +1,5 @@ name=Spacecat -version=1.3.1 +version=1.4.0 author=Arif maintainer=Arif sentence=An Arduino library for ESP8266/ESP32 to makes things easier that requires authentication with an RFID card diff --git a/platformio.ini b/platformio.ini index 07ba3d8..5c0ede0 100644 --- a/platformio.ini +++ b/platformio.ini @@ -8,32 +8,30 @@ ; Please visit documentation for the other options and examples ; https://docs.platformio.org/page/projectconf.html - +; [env:esp32] +; platform = espressif32 +; framework = arduino +; board = esp32dev [env:esp12e] platform = espressif8266 board = esp12e framework = arduino + + monitor_speed = 115200 upload_speed = 921600 -upload_port = COM6 -monitor_port = COM6 -; [env:esp32] -; platform = espressif32 -; framework = arduino -; board = esp32dev +upload_port = COM9 +monitor_port = COM9 + + ; debug_tool = olimex-arm-usb-ocd-h ; build_flags = monitor_flags = ; check_tool = cppcheck, clangtidy -env: - -PLATFORMIO_CI_SRC=examples/ReadCard.ino - -PLATFORMIO_CI_SRC=examples/SimpleValidation.ino lib_deps = https://github.com/miguelbalboa/rfid https://github.com/bblanchon/ArduinoJson -monitor_filters = - \ No newline at end of file diff --git a/src/Spacecat.cpp b/src/Spacecat.cpp index 7eddfc8..bd834e9 100644 --- a/src/Spacecat.cpp +++ b/src/Spacecat.cpp @@ -35,6 +35,10 @@ Spacecat::Spacecat(String username, String password, String deviceName){ #warning Username or Password can not be empty #endif + if(username != NULL && password != NULL){ + Auth = true; + } + if(this->_debug){ Serial.print("[DEBUG] Initialization : "); } @@ -50,11 +54,17 @@ Spacecat::Spacecat(){ Serial.print("[DEBUG] Only Read the card : OK"); } -void Spacecat::intervalReading(int timer){ +void Spacecat::setIntervalReading(int timer){ if(timer && timer != 0){ - this->_INTERVAL_READING_CARD = timer; + this->_PREVIOUS_TIME_READING_CARD = timer; }else{ - this->_INTERVAL_READING_CARD = 1000; // defualt 1 Sec + this->_PREVIOUS_TIME_READING_CARD = 1000; // defualt 1 Sec + } +} + +void Spacecat::setTimeoutPassword(int timer){ + if( timer && timer != 0){ + _TIMER_INSERT_PASSWORD = timer; } } @@ -62,11 +72,17 @@ void Spacecat::setDebug(bool debug){ _debug = debug; } -void Spacecat::init(void){ - SPI.begin(); - this->intervalReading(_INTERVAL_READING_CARD); - this->rc522.PCD_Init(_sdaPin, _resetPin); +void Spacecat::setCallback(Callback_Event callback){ + _callbackEvent = callback; +} +void Spacecat::init(void){ + SPI.begin(); + // client.setCertificate(test_ca_cert); + _callbackEvent = NULL; + this->setIntervalReading(_PREVIOUS_TIME_READING_CARD); + this->rc522.PCD_Init(_sdaPin, _resetPin); + this->isReading = false; #ifdef DEBUG_D Serial.print(F("\n[DEBUG] Library ver: ")); Serial.println(F(lib_version)); @@ -156,55 +172,34 @@ String Spacecat::upTimeDevice(){ return (String)Day +" Day "+ (String)Hour +" Hour, " + (String)Minute + " Min, " + (String)Second + " Sec"; } - -void Spacecat::parseJSON(String payload){ - const size_t capacity = JSON_OBJECT_SIZE(5) + 256; - DynamicJsonDocument doc(capacity); - doc.clear(); - DeserializationError error = deserializeJson(doc, payload); - if(error){ - this->_isreadCard = false; - if(this->_debug){ - Serial.print(F("[DEBUG] deserializeJson() failed: ")); - } - Serial.println(error.c_str()); - }else{ - this->userData._username = doc["name"].as(); - this->userData._codeState = doc["code"].as(); - this->userData._traceID = doc["reference"].as(); - this->userData._messages = doc["messages"].as(); - if(this->userData._codeState == 107){ - _isHavePassword = true; - } - if(_callbackEvent != NULL) - this->_isreadCard = false; - _callbackEvent(this->userData._codeState, this->userData._traceID, this->userData._username, this->userData._messages); - } -} - bool Spacecat::begin(uint8_t SS_PIN){ + if(this->_debug){ Serial.print("[DEBUG] Initialization : "); } - _callbackEvent = NULL; this->_sdaPin = SS_PIN; this->init(); - if(WiFi.status() == WL_CONNECTED){ - if(this->initializeDevice()){ - if(this->_debug){ - Serial.println(F("Done ")); + if(!Auth){ + return true; + }else{ + if(WiFi.status() == WL_CONNECTED){ + if(this->initializeDevice()){ + if(this->_debug){ + Serial.println(F("Done ")); + } + return true; } - return true; + return false; } + return false; } - return false; } bool Spacecat::begin(uint8_t SS_PIN, uint8_t RESET_PIN){ if(this->_debug){ Serial.print("[DEBUG] Initialization : "); } - _callbackEvent = NULL; + this->_sdaPin = SS_PIN; this->_resetPin = RESET_PIN; this->init(); @@ -221,7 +216,140 @@ bool Spacecat::begin(uint8_t SS_PIN, uint8_t RESET_PIN){ String Spacecat::doHash(String id){ - return sha1(id); + // return sha1(id); + return SHA256(id); +} + +void Spacecat::sha256_transform(SHA256_CTX *ctx, const uint8_t data[]) { + uint32_t a, b, c, d, e, f, g, h, i, j, t1, t2, m[64]; + + for (i = 0, j = 0; i < 16; ++i, j += 4) + m[i] = ((uint32_t)data[j] << 24) | ((uint32_t)data[j + 1] << 16) | ((uint32_t)data[j + 2] << 8) | ((uint32_t)data[j + 3]); + for ( ; i < 64; ++i) + m[i] = SIG1(m[i - 2]) + m[i - 7] + SIG0(m[i - 15]) + m[i - 16]; + + a = ctx->state[0]; + b = ctx->state[1]; + c = ctx->state[2]; + d = ctx->state[3]; + e = ctx->state[4]; + f = ctx->state[5]; + g = ctx->state[6]; + h = ctx->state[7]; + + for (i = 0; i < 64; ++i) { + t1 = h + EP1(e) + CH(e,f,g) + k[i] + m[i]; + t2 = EP0(a) + MAJ(a,b,c); + h = g; + g = f; + f = e; + e = d + t1; + d = c; + c = b; + b = a; + a = t1 + t2; + } + + ctx->state[0] += a; + ctx->state[1] += b; + ctx->state[2] += c; + ctx->state[3] += d; + ctx->state[4] += e; + ctx->state[5] += f; + ctx->state[6] += g; + ctx->state[7] += h; +} + +void Spacecat::sha256_init(SHA256_CTX *ctx){ + ctx->datalen = 0; + ctx->bitlen = 0; + ctx->state[0] = 0x6a09e667; + ctx->state[1] = 0xbb67ae85; + ctx->state[2] = 0x3c6ef372; + ctx->state[3] = 0xa54ff53a; + ctx->state[4] = 0x510e527f; + ctx->state[5] = 0x9b05688c; + ctx->state[6] = 0x1f83d9ab; + ctx->state[7] = 0x5be0cd19; +} + +void Spacecat::sha256_update(SHA256_CTX *ctx, const uint8_t data[], size_t len) { + + for (uint32_t i = 0; i < len; ++i) { + ctx->data[ctx->datalen] = data[i]; + ctx->datalen++; + if (ctx->datalen == 64) { + sha256_transform(ctx, ctx->data); + ctx->bitlen += 512; + ctx->datalen = 0; + } + } +} + +void Spacecat::sha256_final(SHA256_CTX *ctx, uint8_t hash[]) { + + uint32_t i = ctx->datalen; + + // Pad whatever data is left in the buffer. + if (ctx->datalen < 56) { + ctx->data[i++] = 0x80; + while (i < 56) + ctx->data[i++] = 0x00; + } else { + ctx->data[i++] = 0x80; + while (i < 64) + ctx->data[i++] = 0x00; + this->sha256_transform(ctx, ctx->data); + memset(ctx->data, 0, 56); + } + + // Append to the padding the total message's length in bits and transform. + ctx->bitlen += ctx->datalen * 8; + ctx->data[63] = ctx->bitlen; + ctx->data[62] = ctx->bitlen >> 8; + ctx->data[61] = ctx->bitlen >> 16; + ctx->data[60] = ctx->bitlen >> 24; + ctx->data[59] = ctx->bitlen >> 32; + ctx->data[58] = ctx->bitlen >> 40; + ctx->data[57] = ctx->bitlen >> 48; + ctx->data[56] = ctx->bitlen >> 56; + sha256_transform(ctx, ctx->data); + + // Since this implementation uses little endian byte ordering and SHA uses big endian, + // reverse all the bytes when copying the final state to the output hash. + for (i = 0; i < 4; ++i) { + hash[i] = (ctx->state[0] >> (24 - i * 8)) & 0x000000ff; + hash[i + 4] = (ctx->state[1] >> (24 - i * 8)) & 0x000000ff; + hash[i + 8] = (ctx->state[2] >> (24 - i * 8)) & 0x000000ff; + hash[i + 12] = (ctx->state[3] >> (24 - i * 8)) & 0x000000ff; + hash[i + 16] = (ctx->state[4] >> (24 - i * 8)) & 0x000000ff; + hash[i + 20] = (ctx->state[5] >> (24 - i * 8)) & 0x000000ff; + hash[i + 24] = (ctx->state[6] >> (24 - i * 8)) & 0x000000ff; + hash[i + 28] = (ctx->state[7] >> (24 - i * 8)) & 0x000000ff; + } +} + +char *btoh(char *dest, uint8_t *src, int len) { + char *d = dest; + while( len-- ) sprintf(d, "%02x", (unsigned char)*src++), d += 2; + return dest; +} + +String Spacecat::SHA256(String data) { + uint8_t data_buffer[data.length()]; + + for(int i=0; idoHash(this->_rfid); uri += "/"; uri += this->getMacAddress(); uri += "/"; @@ -280,13 +408,17 @@ String Spacecat::createUriRegisterID(){ return uri; } - void Spacecat::doRegister(String rfid){ + if(this->_debug){ Serial.print(F("\n[DEBUG] Regsitering ID : ")); } + int start= currentMillis; - this->client.setFingerprint(_certificate); +#ifdef BOARD_ESP8266 + this->client.setInsecure(); + // this->client.setFingerprint(_certificate); +#endif String _data = "rfid=" + rfid; #ifdef USE_HTTPS @@ -301,27 +433,36 @@ void Spacecat::doRegister(String rfid){ this->_http.end(); #ifdef DEBUG_D Serial.printf("[HTTPS] POST... code: %d\n", _httpCode); -#endif +#endif + int end = millis(); + if(this->_debug){ + Serial.println(F("Done")); + Serial.println(String("[DEBUG] Response Time: ") + (end-start) + "ms"); + } if (this->_httpCode > 0) { if(_httpCode == HTTP_CODE_CREATED){ - int end = millis(); - Serial.println(F("Done")); - Serial.println(String("[DEBUG] Response Time: ") + (end-start) + "ms"); isSuccessRegister = true; return; + }else if(_httpCode == HTTP_CODE_CONFLICT){ + isSuccessRegister = false; + if(this->_debug){ + Serial.println(" failed registrering ID"); + } + }else{ + isSuccessRegister = false; + if(this->_debug){ + Serial.println(" failed registrering ID"); + } } - - } - isSuccessRegister = false; - if(this->_debug){ - Serial.println(" failed registrering ID"); } + #ifdef DEBUG_D Serial.printf("[HTTPS] POST... failed, error: %s\n", _http.errorToString(_httpCode).c_str()); #endif - } + } } + bool Spacecat::registerID(){ _isdoRegister = true; if(_isdoRegister){ @@ -334,18 +475,20 @@ bool Spacecat::registerID(){ return false; } -bool Spacecat::pushValue(String value){ +bool Spacecat::pushValue(const char *value){ if(this->_debug){ Serial.print(F("\n[DEBUG] Pushing the value ")); Serial.print(F("\n[DEBUG] Requesting: ")); } int start= currentMillis; if(WiFi.status() == WL_CONNECTED && !_isSuccessPushed){ - String _data = "param_value=" + value + - "&id_reference=" + this->userData._traceID; + // String _data = "param_value=" + value + + // "&id_reference=" + this->userData._traceID; // std::unique_ptrclient(new BearSSL::WiFiClientSecure); - this->client.setFingerprint(_certificate); +#ifdef BOARD_ESP8266 + this->client.setFingerprint(_certificate); +#endif #ifdef USE_HTTPS if(this->_http.begin(client, this->createUriPushValue())){ #else @@ -354,7 +497,7 @@ bool Spacecat::pushValue(String value){ this->_http.addHeader("Content-Type", "application/x-www-form-urlencoded"); this->_http.addHeader("cache-control","no-cache"); this->_http.addHeader("SECRET-KEY", _USERNAME_KEY); - this->_httpCode = _http.POST(_data); + // this->_httpCode = _http.POST(_data); this->_payload = _http.getString(); _isSuccessPushed = true; #ifdef DEBUG_D @@ -384,12 +527,12 @@ bool Spacecat::pushValue(String value){ Serial.println(String("[DEBUG] Response Time: ") + (end-start) + "ms"); Serial.println(F("[DEBUG] Result:")); } - this->parseJSON(_payload); + // this->parseJSON(_payload); return true; - }else{ - if(this->_debug){ - Serial.println("[DEBUG] Failed pushing value"); - } + } else { + if(this->_debug){ + Serial.println("[DEBUG] Failed pushing value"); + } #ifdef DEBUG_D Serial.printf("[HTTPS] POST... failed, error: %s\n", _http.errorToString(_httpCode).c_str()); #endif @@ -401,27 +544,33 @@ bool Spacecat::pushValue(String value){ } -bool Spacecat::enteredPassword(String Password){ +bool Spacecat::enteredPassword(String userPassword){ + if(this->_debug){ Serial.print(F("\n[DEBUG] User inserted password ")); Serial.print(F("\n[DEBUG] Requesting: ")); } - if(WiFi.status() == WL_CONNECTED && _isHavePassword){ - int start= currentMillis; - String _data = - "refid=" + this->userData._traceID + - "&userpwd=" + this->doHash(Password) + - "&mac_address=" + this->getMacAddress() + - "&local_ip_address=" + this->getLocalIP()+ - "&ssid=" + this->getWiFiSSID(); + _requesting = true; + int start= currentMillis; + String _data = + "refid=" + (String) this->user.referenceID + + "&userpwd=" + this->doHash(userPassword) + + "&mac_address=" + this->getMacAddress() + + "&local_ip_address=" + this->getLocalIP() + + "&ssid=" + this->getWiFiSSID(); + +#ifdef BOARD_ESP8266 // std::unique_ptrclient(new BearSSL::WiFiClientSecure); - this->client.setFingerprint(_certificate); - + // this->client.setFingerprint(_certificate); + this->client.setInsecure(); +#endif + #ifdef USE_HTTPS if(this->_http.begin(this->client, this->createUriPassword())){ #else if(this->_http->begin(this->createUriPassword()){ #endif + // this->_http.addHeader("content-type","application/json"); this->_http.addHeader("Content-Type", "application/x-www-form-urlencoded"); this->_http.addHeader("cache-control","no-cache"); @@ -444,32 +593,33 @@ bool Spacecat::enteredPassword(String Password){ Serial.print(F("[DEBUG] Payload : ")); Serial.println(_payload); #endif + + int end =millis(); + this->_http.end(); + _requesting = false; + + if(this->_debug){ + Serial.println(F("Done")); + Serial.println(String("[DEBUG] Response Time: ") + (end-start) + "ms"); + Serial.println(F("[DEBUG] Result:")); + } if (this->_httpCode > 0) { _isHavePassword = false; - _isreadCard = false; - this->_http.end(); - int end =millis(); - if(this->_debug){ - Serial.println(F("Done")); - Serial.println(String("[DEBUG] Response Time: ") + (end-start) + "ms"); - Serial.println(F("[DEBUG] Result:")); - } #ifdef DEBUG_D Serial.printf("[HTTPS] POST... code: %d\n", _httpCode); #endif if(this->_httpCode == HTTP_CODE_OK){ - this->parseJSON(_payload); return true; + } else { + return false; } return false; } - + _isHavePassword = false; #ifdef DEBUG_D Serial.printf("[HTTPsS] GET... failed, error: %s", _http.errorToString(_httpCode).c_str()); #endif - } } - return false; } bool Spacecat::initializeDevice(){ @@ -481,7 +631,7 @@ bool Spacecat::initializeDevice(){ "&ssid=" + this->getWiFiSSID() + "&wifi_strength=" + this->getWifiQuality() + "&mac_address=" + this->getMacAddress() + - "&local_ip_address=" + this->getLocalIP()+ + "&local_ip_address=" + this->getLocalIP() + "&esp_chip_id=" + this->getChipID() + "&core_version=" + this->getCoreVersion() + "&sdk_version=" + ESP.getSdkVersion() + @@ -490,8 +640,16 @@ bool Spacecat::initializeDevice(){ "&uptime=" + this->upTimeDevice() + "&rc522_chip_version=" + "none"; - // std::unique_ptrclient(new BearSSL::WiFiClientSecure); - this->client.setFingerprint(_certificate); +#ifdef BOARD_ESP8266 + // std::unique_ptrclient(new BearSSL::WiFiClientSecure); + // this->client.setFingerprint(_certificate); + this->client.setInsecure(); + +#endif +#ifdef BOARD_ESP32 + // this->client.setCACert(test_ca_cert); + // client.setCertificate(test_ca_cert); +#endif #ifdef USE_HTTPS if(this->_http.begin(client, this->createUriDeviceStatus())){ #else @@ -504,6 +662,7 @@ bool Spacecat::initializeDevice(){ this->_httpCode = _http.POST(_data); this->_payload = _http.getString(); + this->_http.end(); #ifdef DEBUG_PATH_DEVICE_INIT Serial.print(F("[DEBUG] Requesting : ")); @@ -520,6 +679,7 @@ bool Spacecat::initializeDevice(){ Serial.print(F("DEBUG] Payload : ")); Serial.println(_payload); #endif + if (this->_httpCode > 0) { if(this->_httpCode == HTTP_CODE_CREATED){ this->_isSuccessInit = true; @@ -527,13 +687,12 @@ bool Spacecat::initializeDevice(){ }else{ this->_isSuccessInit = false; if(this->_debug){ - Serial.println(F("Upss.. Failed To Initialization Device")); + Serial.println(F("[DEBUG] Upss.. Failed To Initialization Device")); Serial.println(F("[DEBUG] Please restart...")); } return false; - } - this->_http.end(); } + } #ifdef DEBUG_D Serial.printf("[HTTPS] POST...: %s\n", _http.errorToString(_httpCode).c_str()); #endif @@ -542,26 +701,29 @@ bool Spacecat::initializeDevice(){ #ifdef DEBUG_D Serial.printf("[HTTPS] Unable to connect\n"); #endif - if(this->_debug){ - Serial.println(F("Upss.. Unable to connect to server")); - Serial.println(F("[DEBUG] Please restart...")); - } + if(this->_debug){ + Serial.println(F("[DEBUG] Upss.. Unable to connect to server")); + Serial.println(F("[DEBUG] Please restart...")); + } } return false; } -uint8_t Spacecat::validate(String idcard){ - if(this->_debug){ - Serial.print(F("\n[DEBUG] User tapping card ")); - Serial.print(F("\n[DEBUG] Requesting: ")); - } - this->userData._rfid = idcard; - int start= currentMillis; +uint8_t Spacecat::validate(){ + + if(this->_debug){ + Serial.print(F("\n[DEBUG] User tapping card ")); + Serial.print(F("\n[DEBUG] Requesting: ")); + } + int start = currentMillis; #ifdef USE_HTTPS // this->_http.begin(this->createUriGetAccess(),this->_certificate); - // std::unique_ptrclient(new BearSSL::WiFiClientSecure); - this->client.setFingerprint(_certificate); +#ifdef BOARD_ESP8266 + // std::unique_ptrclient(new BearSSL::WiFiClientSecure); + // this->client.setFingerprint(_certificate); + this->client.setInsecure(); +#endif if(this->_http.begin(client, this->createUriGetAccess())){ _requesting = true; #else @@ -573,7 +735,7 @@ uint8_t Spacecat::validate(String idcard){ this->_http.addHeader("SECRET-KEY", _USERNAME_KEY); this->_httpCode = _http.GET(); this->_payload = _http.getString(); - + #ifdef DEBUG_PATH_REQUEST_ACCESS Serial.print("[HTTPS] GET...\n"); Serial.println(this->createUriGetAccess()); @@ -591,135 +753,223 @@ uint8_t Spacecat::validate(String idcard){ if (this->_httpCode > 0) { #ifdef DEBUG_D Serial.printf("[HTTPS] GET... code: %d\n", this->_httpCode); -#endif - int end =millis(); +#endif + + int end = millis(); if(this->_debug){ Serial.println(F("Done")); Serial.print(String("[DEBUG] Response Time: ") + (end-start) + "ms\n"); Serial.println(String("[DEBUG] Result: ")); } + if(this->_httpCode == HTTP_CODE_OK){ - this->parseJSON(_payload); + // this->parseJSON(_payload); + this->_requesting = false; + const size_t capacity = JSON_ARRAY_SIZE(4) + JSON_OBJECT_SIZE(1) + 5*JSON_OBJECT_SIZE(2) + JSON_OBJECT_SIZE(5) + JSON_OBJECT_SIZE(7) + 300; + DynamicJsonDocument doc(capacity); + DeserializationError error = deserializeJson(doc, this->_payload); + if (!error) { + //parse user information + JsonObject profile = doc["profile"]; + this->user.statusCode = doc["code"]; + this->user.referenceID = doc["reference"]; + this->user.messages = (char *) doc["messages"].as(); + this->user.name = (char *) profile["username"].as(); + this->user.isMaster = profile["master"].as(); + this->user.status = profile["status"].as(); + this->user.havePassword = profile["password"].as(); + this->user.email = (char *) profile["email"].as(); + this->user.phoneNumber = (char *) profile["phone_number"].as(); + this->user.amount = profile["amount"]; + // parse rule parameter + this->ruleParameter.amount = doc["parameter"]["rule"]["amount"]; + // parse placement parameters if available + JsonArray parameter_placement = doc["parameter"]["placement"].as(); + if(parameter_placement.size() > 0){ + this->placementParameter.Name1 = (char *) parameter_placement[0]["name"].as(); + this->placementParameter.value1 = parameter_placement[0]["value"]; + this->placementParameter.Name2 = (char *) parameter_placement[1]["name"].as(); + this->placementParameter.value2 = parameter_placement[1]["value"]; + this->placementParameter.Name3 = (char *) parameter_placement[2]["name"].as(); + this->placementParameter.value3 = parameter_placement[2]["value"]; + this->placementParameter.Name4 = (char *) parameter_placement[3]["name"].as(); + this->placementParameter.value4 = parameter_placement[3]["value"]; + } else { + this->placementParameter.Name1 = NULL; + this->placementParameter.value1 = 0; + this->placementParameter.Name2 = NULL; + this->placementParameter.value2 = 0; + this->placementParameter.Name3 = NULL; + this->placementParameter.value3 = 0; + this->placementParameter.Name4 = NULL; + this->placementParameter.value4 = 0; + } + + if(this->user.statusCode == FILL_THE_PASSWORD){ + this->_isHavePassword = true; + _PREVIOUS_TIME_INSERT_PASSWORD = currentMillis; + } + _callbackEvent(true); + } else { + this->_requesting = false; + Serial.print(F("deserializeJson() failed with code ")); + Serial.println(error.c_str()); + _callbackEvent(false); + return false; + } + }else if(_httpCode == HTTP_CODE_NOT_FOUND){ + if(this->_debug){ + Serial.print(F("[DEBUG] Not Found \n")); + } + _callbackEvent(false); #ifdef DEBUG_D Serial.println(F("[DEBUG] Data not found!")); -#endif - if(_callbackEvent != NULL) - this->_isreadCard = false; - this->_requesting = false; - _callbackEvent(109, "-" , "-", "Not Found"); +#endif + this->_requesting = false; return HTTP_CODE_NOT_FOUND; }else if(_httpCode == HTTP_CODE_TOO_MANY_REQUESTS){ -#ifdef DEBUG_D - Serial.println(F("Wait a sec, to many request!")); -#endif - if(_callbackEvent != NULL) - this->_isreadCard = false; - this->_requesting = false; - _callbackEvent(109, "-" , "-", "Not Found"); + if(this->_debug){ + Serial.print(F("[DEBUG] Wait a sec, to many request \n")); + } + _callbackEvent(false); + this->_requesting = false; return HTTP_CODE_TOO_MANY_REQUESTS; } this->_http.end(); } - } + } return false; } -void Spacecat::setSimpleCallback(Callback_Event callback){ - _callbackEvent = callback; -} - void Spacecat::readCard(){ - currentMillis = millis(); - if(!this->rc522.PICC_IsNewCardPresent() || !this->rc522.PICC_ReadCardSerial()){ + currentMillis = millis(); + if(!this->rc522.PICC_IsNewCardPresent() || !this->rc522.PICC_ReadCardSerial()){ return; } - - if(currentMillis > _TIMER_READING_CARD + _INTERVAL_READING_CARD && !this->_isreadCard && !_isHavePassword){ + delay(1); + + if(currentMillis > _TIMER_READING_CARD + _PREVIOUS_TIME_READING_CARD && !this->isReading && !_isHavePassword){ this->_TIMER_READING_CARD = currentMillis; - this->_isreadCard = true; - this->_content = ""; + this->_rfid = ""; + this->isReading = true; for(byte i = 0; i < rc522.uid.size; i++){ - this->_content.concat(String(this->rc522.uid.uidByte[i] < 0x10 ? "0" : "")); - this->_content.concat(String(this->rc522.uid.uidByte[i])); + this->_rfid.concat(String(this->rc522.uid.uidByte[i] < 0x10 ? "0" : "")); + this->_rfid.concat(String(this->rc522.uid.uidByte[i])); } - _content.toUpperCase(); + + // this->user.rfid.toUpperCase(); this->rc522.PICC_HaltA(); this->rc522.PCD_StopCrypto1(); - + isReading = false; + if(_doLoop){ - if(this->_debug){ - Serial.print(String("\n[DEBUG] RFID: ") + (this->doHash(_content.substring(0)))); - } - this->validate(this->doHash(_content.substring(0))); + // if(this->_debug){ + // Serial.print(String("\n[DEBUG] RFID: ") + (this->doHash(this->_rfid.substring(0)))); + // } + this->validate(); return; }else if(this->_isdoRegister && !_doLoop){ if(this->_debug){ - Serial.print(String("\n[DEBUG] RFID: ") + (this->doHash(_content.substring(0)))); + Serial.print(String("\n[DEBUG] RFID: ") + (this->doHash(this->_rfid.substring(0)))); } - this->doRegister(this->doHash(_content.substring(0))); - }else{ - if(this->_debug){ - Serial.print(String("\n[DEBUG] RFID: ") + (this->doHash(_content.substring(0)))); + this->doRegister(this->doHash(this->_rfid.substring(0))); + } else { + this->user.rfid = this->doHash(this->_rfid.substring(0)); + } + } +} + +bool Spacecat::confirm(){ +#ifdef BOARD_ESP8266 + // std::unique_ptrclient(new BearSSL::WiFiClientSecure); + // this->client.setFingerprint(_certificate); + this->client.setInsecure(); +#endif + if(this->_http.begin(client, _protocol+(String) HOST+"/public/api/v1/spacecat/doact/"+ _PASSWORD_KEY+"?")){ + String _data = "id_reference=" +(String) this->user.referenceID; + this->_http.addHeader("Content-Type", "application/x-www-form-urlencoded"); + this->_http.addHeader("cache-control","no-cache"); + this->_http.addHeader("SECRET-KEY", _USERNAME_KEY); + this->_httpCode = _http.POST(_data); + this->_payload = _http.getString(); + this->_http.end(); + if(_httpCode > 0){ + if(_httpCode == HTTP_CODE_OK){ + return true; } + return false; } - _isreadCard = false; - } + return true; + } + return false; } + void Spacecat::loop(){ - _doLoop = true; - currentMillis = millis(); - if(_requesting && _isreadCard){ + this->_doLoop = true; + this->currentMillis = millis(); + + if(this->_isSuccessInit){ + this->readCard(); + } + + // if user have a password, start timer password. + if(this->_isHavePassword){ + if(this->currentMillis - _PREVIOUS_TIME_INSERT_PASSWORD >= _TIMER_INSERT_PASSWORD){ + _PREVIOUS_TIME_INSERT_PASSWORD = this->currentMillis; + this->_isHavePassword = false; + if(this->_debug){ + Serial.println(F("[DEBUG] Password timeout")); + } + } + } + + if(this->_requesting){ // set timeout if server not responding if(currentMillis - _PREVIOUS_TIME_WAITING_HTTP_REQUEST >= _TIMER_TIMEOUT_WAITING_HTTP_REQUEST){ - timer++; - if(timer > timeTimeout){ + this->timer++; + if(this->timer > timeTimeout){ + this->isReading = false; + this->_requesting = false; + this->timer = 0; + + if(this->_debug){ + Serial.println(F("[DEBUG] Request Time Out!")); + } + #ifdef DEBUG_D Serial.println(F("[DEBUG] Request is timeout!")); #endif - if(this->_debug){ - Serial.println(F("[DEBUG] Timeout")); - } - _callbackEvent(105, "-" , "-", "Request timeout"); - _isreadCard = false; - _requesting = false; - timer = 0; } _PREVIOUS_TIME_WAITING_HTTP_REQUEST = currentMillis; } } if(currentMillis - _PREVIOUS_INTERVAL_DEVICE_STATUS >= _INTERVAL_UPDATE_DEVICE_STAUS){ + + this->initializeDevice(); + _PREVIOUS_INTERVAL_DEVICE_STATUS = currentMillis; + #ifdef DEBUG_D Serial.println("[DEBUG] Sending device status"); #endif - this->initializeDevice(); - _PREVIOUS_INTERVAL_DEVICE_STATUS = currentMillis; } - - if(_isSuccessInit){ - this->userData._rfid = ""; - this->readCard(); - } } -void Spacecat::clear(){ - _isHavePassword = false; - _isreadCard = false; - userData._codeState = 0; - userData._traceID = ""; - userData._username = ""; - userData._messages = ""; +bool Spacecat::onlyReadCard(){ + if(!_doLoop){ + readCard(); + } +} +void Spacecat::cancel(){ + _isHavePassword = false; + isReading = false; + if(this->_debug){ - Serial.println(F("[DEBUG] Cleared!")); + Serial.println(F("[DEBUG] Canceled!")); } } - - - - - diff --git a/src/Spacecat.h b/src/Spacecat.h index 63f12e6..4d4a34d 100644 --- a/src/Spacecat.h +++ b/src/Spacecat.h @@ -25,7 +25,7 @@ SOFTWARE. *****************************************************************************/ -#define lib_version "1.3.1" +#define lib_version "1.4.0" #ifndef _Spacecat_h_ #define _Spacecat_h_ @@ -37,34 +37,13 @@ //get from https://github.com/miguelbalboa/rfid #include #include -#include -#include -//Uncomment ENABLE_DEBUG for enable debuging -// #define DEBUG_D - -// Get Access User RFID -// #define DEBUG_PATH_REQUEST_ACCESS -// #define DEBUG_HTTP_CODE_REQUEST_ACCESS -// #define DEBUG_PAYLOAD_REQUEST_ACCESS - -//Intialization Device at startup -// #define DEBUG_PATH_DEVICE_INIT -// #define DEBUG_HTTP_CODE_DEVICE_INIT -// #define DEBUG_PAYLOAD_DEVICE_INIT - -//Password Validation -// #define DEBUG_PATH_PASSWORD -// #define DEBUG_HTTP_CODE_PASSWORD -// #define DEBUG_PAYLOAD_PASSWORD - -// #define DEBUG_PUSH_VALUE -// #define DEBUG_HTTP_CODE_PUSH_VALUE -// #define DEBUG_PAYLOAD_PUSH_VALUE #if defined(ARDUINO_ARCH_ESP8266) #include #include #include + #include + #include #define BOARD_ESP8266 extern "C" { #include "Esp.h" @@ -73,12 +52,15 @@ extern "C" { #elif defined(ARDUINO_ARCH_ESP32) #include #include + #include #include #define BOARD_ESP32 extern "C" { #include "Esp.h" } #endif +// #define DEBUG_D + //uncomnet USE_HTTPS if you want use http:// #define USE_HTTPS @@ -86,11 +68,11 @@ extern "C" { #define _protocol "http://" #else #define _protocol "https://" - #endif #define HOST "rfid.asyarif.net" #define PORT 80 +#define PORT_S 443 #define PROJECT_N_ACTIVE 101 #define USER_N_ACTIVE 102 #define PLACEMENT_N_ACTIVE 103 @@ -100,35 +82,88 @@ extern "C" { #define FILL_THE_PASSWORD 107 #define REACH_THE_LIMIT 108 #define ERR_NOT_FOUND 109 -typedef void (*Callback_Event)(int code, String refrence , String name, String messages); +#define PASSWORD_CORRECT 111 +#define PARAM_CONFIRM 112 + +typedef void (*Callback_Event)(bool isUserFound); + + struct Users{ + uint16_t statusCode; + int referenceID; + bool isMaster; + bool status; + bool havePassword; + String rfid; + char* messages; + char* name; + char* email; + char* phoneNumber; + int amount; + }; + + // this rule amount only show before processed (last amount value) + struct RuleParam{ + int amount; + }; + + struct placementParam{ + char* Name1; + int value1; + char* Name2; + int value2; + char* Name3; + int value3; + char* Name4; + int value4; + }; + + typedef struct { + uint8_t data[64]; + uint32_t datalen; + uint32_t state[8]; + unsigned long long bitlen; + } SHA256_CTX; + + static const uint32_t k[64] = { + 0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5, + 0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174, + 0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da, + 0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967, + 0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85, + 0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070, + 0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3, + 0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2 + }; + class Spacecat{ bool _debug = true; private: - - bool _isreadCard ,_requesting,_isSuccessInit, _isHavePassword, _doLoop, _isSuccessPushed, _isdoRegister, isSuccessRegister = false; + Callback_Event _callbackEvent; + bool isReading, Auth, _requesting, _isSuccessInit, _isHavePassword, _doLoop, _isSuccessPushed, _isdoRegister, isSuccessRegister = false; int _httpCode; + String _rfid; unsigned int _port = PORT; uint8_t _sdaPin; uint8_t _resetPin; uint8_t timer; uint8_t timeTimeout = 3; // default is three seconds - #define _TIMER_TIMEOUT_WAITING_HTTP_REQUEST 1000 + #define _TIMER_TIMEOUT_WAITING_HTTP_REQUEST 5000 #define _INTERVAL_UPDATE_DEVICE_STAUS 60000 - #define _INTERVAL_INSERT_PASSWORD 5000 - unsigned long _INTERVAL_READING_CARD, _TIMER_READING_CARD, _TIMER_WAITING_INSERT_PASSWORD, _PREVIOUS_TIME_WAITING_HTTP_REQUEST, _PREVIOUS_INTERVAL_DEVICE_STATUS = 0; + int _TIMER_INSERT_PASSWORD = 5000; //default + unsigned long _PREVIOUS_TIME_READING_CARD, _TIMER_READING_CARD, _PREVIOUS_TIME_WAITING_HTTP_REQUEST, _PREVIOUS_INTERVAL_DEVICE_STATUS, _PREVIOUS_TIME_INSERT_PASSWORD = 0; unsigned long currentMillis; - String _content, _payload; + String _payload; String _USERNAME_KEY; String _PASSWORD_KEY; String _DEVICE_NAME; String _DEVICE_TYPE = "RFID-READER"; - uint8_t validate(String idcard); - String getLocalIP(); - String getMacAddress(); - String getWiFiSSID(); + uint8_t validate(); + String getLocalIP(); + String getMacAddress(); + String getWiFiSSID(); uint8_t getChipID(); - String getCoreVersion(); + String getCoreVersion(); uint8_t getBootVersion(); uint8_t getBootMode(); String createUriGetAccess(); @@ -142,38 +177,91 @@ class Spacecat{ void _setLed(uint8_t _ledPin); void init(); void doRegister(String rfid); - void parseJSON(String payload); + void readCard(); bool createRequest(); bool initializeDevice(); HTTPClient _http; WiFiClientSecure client; MFRC522 rc522; - Callback_Event _callbackEvent; - struct rfidData{ - int _codeState; - String _username; - String _traceID; - String _messages; - String _rfid; - } userData; -public: + + const char* _certificate = "EE:1A:A8:59:25:F2:67:6B:4D:D2:BB:45:DE:AE:37:C2:CF:4C:97:A1"; - void loop(); - void clear(); - void setSimpleCallback(Callback_Event callback); - void setRawCallback(); - void intervalReading(int time); - void readCard(); - void setDebug(bool debug); + //hash + char hex[256]; + uint8_t data[256]; + uint8_t hash[32]; + #define SHA256_BLOCK_SIZE 32 + void sha256_init(SHA256_CTX *ctx); + void sha256_update(SHA256_CTX *ctx, const uint8_t data[], size_t len); + void sha256_final(SHA256_CTX *ctx, uint8_t hash[]); + void sha256_transform(SHA256_CTX *ctx, const uint8_t data[]); + String SHA256(String data); + #define ROTLEFT(a,b) (((a) << (b)) | ((a) >> (32-(b)))) + #define ROTRIGHT(a,b) (((a) >> (b)) | ((a) << (32-(b)))) + #define CH(x,y,z) (((x) & (y)) ^ (~(x) & (z))) + #define MAJ(x,y,z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z))) + #define EP0(x) (ROTRIGHT(x,2) ^ ROTRIGHT(x,13) ^ ROTRIGHT(x,22)) + #define EP1(x) (ROTRIGHT(x,6) ^ ROTRIGHT(x,11) ^ ROTRIGHT(x,25)) + #define SIG0(x) (ROTRIGHT(x,7) ^ ROTRIGHT(x,18) ^ ((x) >> 3)) + #define SIG1(x) (ROTRIGHT(x,17) ^ ROTRIGHT(x,19) ^ ((x) >> 10)) + + +public: + Users user; + RuleParam ruleParameter; + placementParam placementParameter; Spacecat(String Username, String Password, String DeviceName); Spacecat(); + int getWifiQuality(); + void loop(); + void cancel(); + void setIntervalReading(int time); + void setTimeoutPassword(int time); + void setDebug(bool debug); + void setCallback(Callback_Event callback); + bool onlyReadCard(); bool registerID(); + bool confirm(); bool enteredPassword(String user_password); - bool pushValue(String value); + bool pushValue(const char *value); bool begin(uint8_t SS_PIN); bool begin(uint8_t SS_PIN, uint8_t RESET_PIN); - int getWifiQuality(); + + const char* test_ca_cert = \ + "-----BEGIN CERTIFICATE-----\n" \ + "MIIFbTCCBFWgAwIBAgISBJIMiyUiBYnaGKpPTi+4arjUMA0GCSqGSIb3DQEBCwUA\n" \ + "MEoxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1MZXQncyBFbmNyeXB0MSMwIQYDVQQD\n" \ + "ExpMZXQncyBFbmNyeXB0IEF1dGhvcml0eSBYMzAeFw0yMDA1MTgxNzQzMjlaFw0y\n" \ + "MDA4MTYxNzQzMjlaMBsxGTAXBgNVBAMTEHJmaWQuYXN5YXJpZi5uZXQwggEiMA0G\n" \ + "CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC1lsIAJd+ViMLCfXynxHyRO2tGiPzp\n" \ + "D+S0lZxoafUltXriZsZyNBmlavGO71EFABY7BzJ5cMLX1xVWY5CN55YJNmlp3I/U\n" \ + "QwQcv4O6r5sq34GA8yRFk/QdFPJecB9GiiI4vCFcCGhoqJVUmVAP4B5MndLqKRM1\n" \ + "Bg1DV3fCyD1AXtR7kV05ABLcQxyVtrE2ln2Dn7z+QMGKtSxcbGAIoU2ZAbr03tq4\n" \ + "PEOszruoLCZxjVcYerJfSFqppAkrjJT1wxz7m4ltf9BQ6RyePoSFcfF1a4xfNf9z\n" \ + "zq/x1YNh8dolS0yz+BrKWVaZzpep54V/xvW+q1lwRY6sdixBSeZsoQM3AgMBAAGj\n" \ + "ggJ6MIICdjAOBgNVHQ8BAf8EBAMCBaAwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsG\n" \ + "AQUFBwMCMAwGA1UdEwEB/wQCMAAwHQYDVR0OBBYEFOLwUUbu1YrsrmjYTYybisrG\n" \ + "XPiIMB8GA1UdIwQYMBaAFKhKamMEfd265tE5t6ZFZe/zqOyhMG8GCCsGAQUFBwEB\n" \ + "BGMwYTAuBggrBgEFBQcwAYYiaHR0cDovL29jc3AuaW50LXgzLmxldHNlbmNyeXB0\n" \ + "Lm9yZzAvBggrBgEFBQcwAoYjaHR0cDovL2NlcnQuaW50LXgzLmxldHNlbmNyeXB0\n" \ + "Lm9yZy8wMQYDVR0RBCowKIIQcmZpZC5hc3lhcmlmLm5ldIIUd3d3LnJmaWQuYXN5\n" \ + "YXJpZi5uZXQwTAYDVR0gBEUwQzAIBgZngQwBAgEwNwYLKwYBBAGC3xMBAQEwKDAm\n" \ + "BggrBgEFBQcCARYaaHR0cDovL2Nwcy5sZXRzZW5jcnlwdC5vcmcwggEDBgorBgEE\n" \ + "AdZ5AgQCBIH0BIHxAO8AdQBep3P531bA57U2SH3QSeAyepGaDIShEhKEGHWWgXFF\n" \ + "WAAAAXIpGRd4AAAEAwBGMEQCIEyy598Hp+3QwWjR3BAXdrOhZUcI4Y70Y9h9zUw/\n" \ + "HsY8AiABiFAJI01HD6KfAOFEu/de8CJ4n52QbwzyA340yp3DAgB2ALIeBcyLos2K\n" \ + "IE6HZvkruYolIGdr2vpw57JJUy3vi5BeAAABcikZF2UAAAQDAEcwRQIhAMHOubrb\n" \ + "13evPJIplv81Ve+7G/tO7lgzTbJ5ZByMb8XrAiATjHcB1k5TfoZHIisgw1yQzR+Y\n" \ + "HIT62grhF297NkazAzANBgkqhkiG9w0BAQsFAAOCAQEAgtYcnbDcwdBx1+apkG86\n" \ + "wnrRj6zHjUO4vXlu0O4a/dRKUHjKZqj3G4+TALPczG/iS+eQVz+QtOCXfbzFQKkQ\n" \ + "Qtczi3HFzD3jGULmnpKDcjasJMFd0xNO3gS42bZpgiC82jx4pai5Nj5p3ZyEgXDD\n" \ + "j13vQ2F5cpYY6EMd1YDuHM84G1v1ouXm7fahRZnO1jKSuM8gSqCUsMQxIDb4JX5R\n" \ + "JDMXQJU+ju76XnvNRR4SktRHxkmBXOZrxSYIiRudFIV6oNzlrVR0RfLzhVpKc3HL\n" \ + "qarJmb7E67NqKIUhjbdV0GI/XGOpizZRgsG7bvkxSxCflOKUN1EmERI6dfI34GO1\n" \ + "SA==\n" \ + "-----END CERTIFICATE-----\n" \ + ; }; #endif \ No newline at end of file