From 6429609731416cd4e6e05b27f783e7834891be67 Mon Sep 17 00:00:00 2001 From: Koki Shinjo Date: Thu, 25 Jan 2024 13:46:56 +0900 Subject: [PATCH] Add cpp format (#30) --- .clang-format | 2 + .github/workflows/clang_format.yml | 24 + arduino_lib/ArduinoAtomS3Hardware.h | 48 +- arduino_lib/devices/stickv2_util.h | 42 +- arduino_lib/devices/uwb_module_util.h | 61 +-- arduino_lib/iot_com_util/Time.h | 57 ++- arduino_lib/iot_com_util/iot_client_util.h | 108 +++-- arduino_lib/iot_com_util/iot_host_util.h | 20 +- arduino_lib/sdp/esp_now.h | 32 +- arduino_lib/sdp/packet_creator.h | 158 +++---- arduino_lib/sdp/packet_parser.h | 108 ++--- arduino_lib/sdp/packet_util.h | 125 +++-- arduino_lib/sdp/sdp.h | 512 ++++++++++----------- arduino_lib/sdp/sdp_util.h | 2 +- arduino_lib/utils/config_loader.h | 34 +- arduino_lib/web_services/sesami_util.h | 275 +++++------ arduino_lib/web_services/switchbot_util.h | 233 +++++----- 17 files changed, 869 insertions(+), 972 deletions(-) create mode 100644 .clang-format create mode 100644 .github/workflows/clang_format.yml diff --git a/.clang-format b/.clang-format new file mode 100644 index 00000000..880cdc75 --- /dev/null +++ b/.clang-format @@ -0,0 +1,2 @@ +BasedOnStyle: Google +ColumnLimit: 0 diff --git a/.github/workflows/clang_format.yml b/.github/workflows/clang_format.yml new file mode 100644 index 00000000..be2e0c23 --- /dev/null +++ b/.github/workflows/clang_format.yml @@ -0,0 +1,24 @@ +name: Clang formatting + +on: + push: + branches: [master] + pull_request: + branches: [master] + +jobs: + clang-format-check: + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v2 + - name: Install Clang Format + run: sudo apt-get install -y clang-format + - name: Check Clang Format for arduino_lib + run: | + find arduino_lib -name '*.cpp' -o -name '*.h' | xargs clang-format -i + git diff --exit-code + - name: Check Clang Format for sketches + run: | + find arduino_lib -name '*.cpp' -o -name '*.h' | xargs clang-format -i + git diff --exit-code \ No newline at end of file diff --git a/arduino_lib/ArduinoAtomS3Hardware.h b/arduino_lib/ArduinoAtomS3Hardware.h index de6c7136..00bb14d3 100644 --- a/arduino_lib/ArduinoAtomS3Hardware.h +++ b/arduino_lib/ArduinoAtomS3Hardware.h @@ -2,57 +2,35 @@ #define SERIAL_CLASS HWCDC -class ArduinoHardware -{ -public: - ArduinoHardware(SERIAL_CLASS* io, long baud = 57600) - { +class ArduinoHardware { + public: + ArduinoHardware(SERIAL_CLASS* io, long baud = 57600) { iostream = io; baud_ = baud; } - ArduinoHardware() - { + ArduinoHardware() { iostream = &Serial; baud_ = 57600; } - ArduinoHardware(ArduinoHardware& h) - { + ArduinoHardware(ArduinoHardware& h) { this->iostream = h.iostream; this->baud_ = h.baud_; } - void setBaud(long baud) - { - this->baud_ = baud; - } + void setBaud(long baud) { this->baud_ = baud; } - int getBaud() - { - return baud_; - } + int getBaud() { return baud_; } - void init() - { - iostream->begin(baud_); - } + void init() { iostream->begin(baud_); } - int read() - { - return iostream->read(); - }; - void write(uint8_t* data, int length) - { - for (int i = 0; i < length; i++) - iostream->write(data[i]); + int read() { return iostream->read(); }; + void write(uint8_t* data, int length) { + for (int i = 0; i < length; i++) iostream->write(data[i]); } - unsigned long time() - { - return millis(); - } + unsigned long time() { return millis(); } -protected: + protected: SERIAL_CLASS* iostream; long baud_; }; - diff --git a/arduino_lib/devices/stickv2_util.h b/arduino_lib/devices/stickv2_util.h index c18d78cd..e3c249bf 100644 --- a/arduino_lib/devices/stickv2_util.h +++ b/arduino_lib/devices/stickv2_util.h @@ -2,36 +2,34 @@ #define STICKV2_UTIL_H #include - #include #define BUFSIZE 2048 -bool send_data_to_serial(HardwareSerial &serial, StaticJsonDocument &doc) -{ - String request; - serializeJson(doc, request); - serial.println(request); - return true; +bool send_data_to_serial(HardwareSerial &serial, + StaticJsonDocument &doc) { + String request; + serializeJson(doc, request); + serial.println(request); + return true; } -bool read_data_from_serial(HardwareSerial &serial, StaticJsonDocument &doc) -{ - String response = serial.readStringUntil('\n'); - DeserializationError error = deserializeJson(doc, response); - if (error) - { - return false; - } - return true; +bool read_data_from_serial(HardwareSerial &serial, + StaticJsonDocument &doc) { + String response = serial.readStringUntil('\n'); + DeserializationError error = deserializeJson(doc, response); + if (error) { + return false; + } + return true; } -bool set_object_recognition_model(HardwareSerial &serial, const String &model_path) -{ - StaticJsonDocument doc; - doc["function"] = "object_recognition"; - doc["args"][0] = model_path; - return send_data_to_serial(serial, doc); +bool set_object_recognition_model(HardwareSerial &serial, + const String &model_path) { + StaticJsonDocument doc; + doc["function"] = "object_recognition"; + doc["args"][0] = model_path; + return send_data_to_serial(serial, doc); } #endif \ No newline at end of file diff --git a/arduino_lib/devices/uwb_module_util.h b/arduino_lib/devices/uwb_module_util.h index 0b6d3a11..cd1af13b 100644 --- a/arduino_lib/devices/uwb_module_util.h +++ b/arduino_lib/devices/uwb_module_util.h @@ -2,6 +2,7 @@ #define UWB_MODULE_UTIL_H #include + #include /** @@ -14,14 +15,11 @@ String testUWB(HardwareSerial& serial); bool resetUWB(HardwareSerial& serial); bool initUWB(bool tag, int id, HardwareSerial& serial); -std::optional readUWB(HardwareSerial& serial, int timeout = 1000) -{ +std::optional readUWB(HardwareSerial& serial, int timeout = 1000) { String DATA; auto start = millis(); - while (timeout > millis() - start) - { - if (serial.available()) - { + while (timeout > millis() - start) { + if (serial.available()) { DATA = serial.readStringUntil('\n'); return DATA; } @@ -29,15 +27,12 @@ std::optional readUWB(HardwareSerial& serial, int timeout = 1000) return std::nullopt; } -std::optional> getDistanceUWB(HardwareSerial& serial) -{ +std::optional> getDistanceUWB(HardwareSerial& serial) { std::optional ret = readUWB(serial); - if (ret) - { + if (ret) { auto data = *ret; auto index = data.indexOf(':'); - if (index != -1) - { + if (index != -1) { auto id_str = data.substring(0, index); id_str.replace(String("an"), String("")); auto id = id_str.toInt(); @@ -50,59 +45,45 @@ std::optional> getDistanceUWB(HardwareSerial& serial) return std::nullopt; } -void clearReadUWB(HardwareSerial& serial, int timeout = 1000) -{ +void clearReadUWB(HardwareSerial& serial, int timeout = 1000) { auto start = millis(); - while (timeout > millis() - start) - { - if (serial.available()) - { + while (timeout > millis() - start) { + if (serial.available()) { serial.readStringUntil('\n'); } } } -String testUWB(HardwareSerial& serial) -{ +String testUWB(HardwareSerial& serial) { serial.write("AT\r\n"); delay(100); auto ret = readUWB(serial); - if (ret) - { + if (ret) { return *ret; - } - else - { + } else { return "No response"; } } -bool resetUWB(HardwareSerial& serial) -{ +bool resetUWB(HardwareSerial& serial) { serial.write("AT+RST\r\n"); delay(500); auto ret = readUWB(serial); clearReadUWB(serial); - if (ret) - { + if (ret) { return true; - } - else - { + } else { return false; } } -bool initUWB(bool tag, int id, HardwareSerial& serial) -{ +bool initUWB(bool tag, int id, HardwareSerial& serial) { String DATA; auto ret = resetUWB(serial); - if (!ret) - { + if (!ret) { return false; } - if (tag) - { + if (tag) { serial.printf("AT+anchor_tag=0\r\n", id); delay(100); readUWB(serial); @@ -116,9 +97,7 @@ bool initUWB(bool tag, int id, HardwareSerial& serial) serial.write("AT+switchdis=1\r\n"); delay(100); readUWB(serial); - } - else - { + } else { serial.printf("AT+anchor_tag=1,%d\r\n", id); delay(100); readUWB(serial); diff --git a/arduino_lib/iot_com_util/Time.h b/arduino_lib/iot_com_util/Time.h index 8fa63209..25b3d23d 100644 --- a/arduino_lib/iot_com_util/Time.h +++ b/arduino_lib/iot_com_util/Time.h @@ -2,9 +2,20 @@ The MIT License (MIT) Copyright (c) 2017 kerikun11 - Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: The above copyright + notice and this permission notice shall be included in all copies or + substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", + WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO + THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE + FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR + THE USE OR OTHER DEALINGS IN THE SOFTWARE. https://www.kerislab.jp/posts/2017-04-26-esp32-time/ */ @@ -16,18 +27,19 @@ #include #include #include + #include + #include "esp32-hal-log.h" class Time; -class Time -{ -public: +class Time { + public: Time(char *time_zone = "JST-9") : time_zone(time_zone) {} bool set_time(); -private: + private: WiFiUDP udp; const char *time_zone; bool getNtpTime(struct timeval *tvp); @@ -39,12 +51,10 @@ class Time class Time Time; -bool Time::set_time() -{ +bool Time::set_time() { udp.begin(NTP_LOCAL_PORT); struct timeval tv; - if (!getNtpTime(&tv)) - { + if (!getNtpTime(&tv)) { return false; } struct timezone tz; @@ -58,33 +68,29 @@ bool Time::set_time() return true; } -bool Time::getNtpTime(struct timeval *tvp) -{ - while (udp.parsePacket() > 0) - { +bool Time::getNtpTime(struct timeval *tvp) { + while (udp.parsePacket() > 0) { delay(1); } log_i("Transmiting NTP Request..."); byte packetBuffer[NTP_PACKET_SIZE]; memset(packetBuffer, 0, NTP_PACKET_SIZE); - packetBuffer[0] = 0b11100011; // LI, Version, Mode - packetBuffer[1] = 0; // Stratum, or type of clock - packetBuffer[2] = 6; // Polling Interval - packetBuffer[3] = 0xEC; // Peer Clock Precision + packetBuffer[0] = 0b11100011; // LI, Version, Mode + packetBuffer[1] = 0; // Stratum, or type of clock + packetBuffer[2] = 6; // Polling Interval + packetBuffer[3] = 0xEC; // Peer Clock Precision // 8 bytes of zero for Root Delay & Root Dispersion packetBuffer[12] = 49; packetBuffer[13] = 0x4E; packetBuffer[14] = 49; packetBuffer[15] = 52; - udp.beginPacket(NTP_SERVER_IPADDRESS, 123); // NTP requests are to port 123 + udp.beginPacket(NTP_SERVER_IPADDRESS, 123); // NTP requests are to port 123 udp.write(packetBuffer, NTP_PACKET_SIZE); udp.endPacket(); uint32_t time_stamp = millis(); - while (millis() - time_stamp < 1500) - { + while (millis() - time_stamp < 1500) { int size = udp.parsePacket(); - if (size >= NTP_PACKET_SIZE) - { + if (size >= NTP_PACKET_SIZE) { log_i("Received NTP Response"); udp.read(packetBuffer, NTP_PACKET_SIZE); unsigned long secsSince1900, afterTheDecimalPoint; @@ -97,7 +103,8 @@ bool Time::getNtpTime(struct timeval *tvp) afterTheDecimalPoint |= (unsigned long)packetBuffer[46] << 8; afterTheDecimalPoint |= (unsigned long)packetBuffer[47] << 0; tvp->tv_sec = secsSince1900 - 2208988800UL; - tvp->tv_usec = (float)afterTheDecimalPoint * 1000000 / (uint64_t)0x100000000; + tvp->tv_usec = + (float)afterTheDecimalPoint * 1000000 / (uint64_t)0x100000000; log_d("%d,%d", tvp->tv_sec, tvp->tv_usec); return true; } diff --git a/arduino_lib/iot_com_util/iot_client_util.h b/arduino_lib/iot_com_util/iot_client_util.h index 1f351d6e..0e61da68 100644 --- a/arduino_lib/iot_com_util/iot_client_util.h +++ b/arduino_lib/iot_com_util/iot_client_util.h @@ -1,77 +1,73 @@ #ifndef IOT_WIFI_UTIL_H #define IOT_WIFI_UTIL_H +#include #include #include -#include #include #include "iot_com_util/Time.h" -bool initWiFi(const char *ssid, const char *password, LGFX_Sprite &sprite, LGFX &lcd, WiFiMulti &WiFiMulti) -{ - WiFiMulti.addAP(ssid, password); - sprite.fillScreen(0xFFFFFF); - sprite.setCursor(0, 0); - sprite.printf("Waiting connect to WiFi: %s ...", ssid); +bool initWiFi(const char *ssid, const char *password, LGFX_Sprite &sprite, + LGFX &lcd, WiFiMulti &WiFiMulti) { + WiFiMulti.addAP(ssid, password); + sprite.fillScreen(0xFFFFFF); + sprite.setCursor(0, 0); + sprite.printf("Waiting connect to WiFi: %s ...", ssid); + sprite.pushSprite(0, lcd.height() / 3); + int sum = 0; + while (WiFiMulti.run() != WL_CONNECTED) { + sprite.print("."); sprite.pushSprite(0, lcd.height() / 3); - int sum = 0; - while (WiFiMulti.run() != WL_CONNECTED) - { - sprite.print("."); - sprite.pushSprite(0, lcd.height() / 3); - delay(1000); - sum += 1; - if (sum == 5) - { - sprite.print("Conncet failed!"); - sprite.pushSprite(0, lcd.height() / 3); - return false; - } + delay(1000); + sum += 1; + if (sum == 5) { + sprite.print("Conncet failed!"); + sprite.pushSprite(0, lcd.height() / 3); + return false; } + } - if (not Ping.ping("www.google.com")) - { - sprite.fillScreen(0xFFFFFF); - sprite.setCursor(0, 0); - sprite.print("Ping failed!"); - sprite.pushSprite(0, lcd.height() / 3); - return false; - } + if (not Ping.ping("www.google.com")) { sprite.fillScreen(0xFFFFFF); - sprite.println("WiFi connected"); - sprite.print("IP address: "); - sprite.println(WiFi.localIP()); + sprite.setCursor(0, 0); + sprite.print("Ping failed!"); sprite.pushSprite(0, lcd.height() / 3); - Time.set_time(); - delay(500); - return true; + return false; + } + sprite.fillScreen(0xFFFFFF); + sprite.println("WiFi connected"); + sprite.print("IP address: "); + sprite.println(WiFi.localIP()); + sprite.pushSprite(0, lcd.height() / 3); + Time.set_time(); + delay(500); + return true; } -void init_screen(LGFX &lcd, LGFX_Sprite &sprite_device_info, LGFX_Sprite &sprite_event_info) -{ - lcd.init(); - lcd.setRotation(1); - lcd.setBrightness(128); - lcd.setColorDepth(24); - lcd.fillScreen(0xFFFFFF); - sprite_device_info.createSprite(lcd.width(), lcd.height() / 3); - sprite_event_info.createSprite(lcd.width(), lcd.height() / 3 * 2); - sprite_device_info.fillScreen(0xFFFFFF); - sprite_event_info.fillScreen(0xFFFFFF); - sprite_device_info.setTextColor(0x000000); - sprite_event_info.setTextColor(0x000000); - sprite_device_info.setTextSize(1); - sprite_event_info.setTextSize(1); +void init_screen(LGFX &lcd, LGFX_Sprite &sprite_device_info, + LGFX_Sprite &sprite_event_info) { + lcd.init(); + lcd.setRotation(1); + lcd.setBrightness(128); + lcd.setColorDepth(24); + lcd.fillScreen(0xFFFFFF); + sprite_device_info.createSprite(lcd.width(), lcd.height() / 3); + sprite_event_info.createSprite(lcd.width(), lcd.height() / 3 * 2); + sprite_device_info.fillScreen(0xFFFFFF); + sprite_event_info.fillScreen(0xFFFFFF); + sprite_device_info.setTextColor(0x000000); + sprite_event_info.setTextColor(0x000000); + sprite_device_info.setTextSize(1); + sprite_event_info.setTextSize(1); } -void show_device_info(const char *message, LGFX_Sprite &sprite, LGFX &lcd) -{ - sprite.fillScreen(0xFFFFFF); - sprite.setCursor(0, 0); - sprite.println(message); - sprite.pushSprite(0, lcd.height() / 3); +void show_device_info(const char *message, LGFX_Sprite &sprite, LGFX &lcd) { + sprite.fillScreen(0xFFFFFF); + sprite.setCursor(0, 0); + sprite.println(message); + sprite.pushSprite(0, lcd.height() / 3); } -#endif // IOT_WIFI_UTIL_H \ No newline at end of file +#endif // IOT_WIFI_UTIL_H \ No newline at end of file diff --git a/arduino_lib/iot_com_util/iot_host_util.h b/arduino_lib/iot_com_util/iot_host_util.h index 5e5859aa..4865811f 100644 --- a/arduino_lib/iot_com_util/iot_host_util.h +++ b/arduino_lib/iot_com_util/iot_host_util.h @@ -3,33 +3,27 @@ #include -String send_serial_command(String command, int timeout_duration = 5000) -{ +String send_serial_command(String command, int timeout_duration = 5000) { Serial2.print(command.c_str()); auto timeout = millis() + timeout_duration; - while (millis() < timeout) - { + while (millis() < timeout) { delay(100); - if (Serial2.available()) - { + if (Serial2.available()) { return Serial2.readStringUntil('\n'); } } return ""; } -void clear_recv_buf(int duration = 5000) -{ +void clear_recv_buf(int duration = 5000) { auto timeout = millis() + duration; - while (millis() < timeout) - { + while (millis() < timeout) { delay(100); - if (Serial2.available()) - { + if (Serial2.available()) { Serial2.readStringUntil('\n'); } } return; } -#endif // IOT_HOST_UTIL_H +#endif // IOT_HOST_UTIL_H diff --git a/arduino_lib/sdp/esp_now.h b/arduino_lib/sdp/esp_now.h index 1b5b1093..8b569dd0 100644 --- a/arduino_lib/sdp/esp_now.h +++ b/arduino_lib/sdp/esp_now.h @@ -1,25 +1,21 @@ #pragma once -#include -#include #include - +#include +#include #include -bool init_esp_now(uint8_t *mac_address, esp_now_recv_cb_t callback_receive) -{ - // Read device mac address - esp_read_mac(mac_address, ESP_MAC_WIFI_STA); +bool init_esp_now(uint8_t *mac_address, esp_now_recv_cb_t callback_receive) { + // Read device mac address + esp_read_mac(mac_address, ESP_MAC_WIFI_STA); - WiFi.mode(WIFI_STA); - WiFi.disconnect(); - if (esp_now_init() != ESP_OK) - { - return false; - } - if (callback_receive != NULL) - { - esp_now_register_recv_cb(callback_receive); - } - return true; + WiFi.mode(WIFI_STA); + WiFi.disconnect(); + if (esp_now_init() != ESP_OK) { + return false; + } + if (callback_receive != NULL) { + esp_now_register_recv_cb(callback_receive); + } + return true; } \ No newline at end of file diff --git a/arduino_lib/sdp/packet_creator.h b/arduino_lib/sdp/packet_creator.h index a3b9c81d..4d81b3ff 100644 --- a/arduino_lib/sdp/packet_creator.h +++ b/arduino_lib/sdp/packet_creator.h @@ -1,38 +1,41 @@ #ifndef SMART_DEVICE_PROTOCOL_PACKET_CREATOR_H__ #define SMART_DEVICE_PROTOCOL_PACKET_CREATOR_H__ -#include -#include +#include #include -#include +#include +#include #include "sdp/packet_util.h" -void generate_meta_frame(uint8_t *packet, const char *device_name, const char *packet_description_01, - const char *serialization_format_01, const char *packet_description_02, - const char *serialization_format_02, const char *packet_description_03, - const char *serialization_format_03) -{ +void generate_meta_frame(uint8_t *packet, const char *device_name, + const char *packet_description_01, + const char *serialization_format_01, + const char *packet_description_02, + const char *serialization_format_02, + const char *packet_description_03, + const char *serialization_format_03) { *(uint16_t *)(packet + 0) = smart_device_protocol::Packet::PACKET_TYPE_META; strncpy((char *)(packet + 2), device_name, 20); strncpy((char *)(packet + 2 + 20), packet_description_01, 64); strncpy((char *)(packet + 2 + 20 + 64), serialization_format_01, 10); strncpy((char *)(packet + 2 + 20 + 64 + 10), packet_description_02, 64); - strncpy((char *)(packet + 2 + 20 + 64 + 10 + 64), serialization_format_02, 10); - strncpy((char *)(packet + 2 + 20 + 64 + 10 + 64 + 10), packet_description_03, 64); - strncpy((char *)(packet + 2 + 20 + 64 + 10 + 64 + 10 + 64), serialization_format_03, 10); + strncpy((char *)(packet + 2 + 20 + 64 + 10 + 64), serialization_format_02, + 10); + strncpy((char *)(packet + 2 + 20 + 64 + 10 + 64 + 10), packet_description_03, + 64); + strncpy((char *)(packet + 2 + 20 + 64 + 10 + 64 + 10 + 64), + serialization_format_03, 10); } -bool generate_data_frame(uint8_t *packet, const char *packet_description, const char *serialization_format, - std::vector &data) -{ - if (not is_consistent_serialization_format(serialization_format, data)) - { +bool generate_data_frame(uint8_t *packet, const char *packet_description, + const char *serialization_format, + std::vector &data) { + if (not is_consistent_serialization_format(serialization_format, data)) { return false; } - if (strlen(serialization_format) != std::vector(data).size()) - { + if (strlen(serialization_format) != std::vector(data).size()) { return false; } *(uint16_t *)(packet + 0) = smart_device_protocol::Packet::PACKET_TYPE_DATA; @@ -41,50 +44,44 @@ bool generate_data_frame(uint8_t *packet, const char *packet_description, const auto packet_data_p = packet + 2 + 64 + 10; auto it = data.begin(); int index_sf = 0; - while (it != data.end()) - { + while (it != data.end()) { std::string str; - switch (serialization_format[index_sf]) - { - case 'i': // std::holds_alternative(*it) - *(int32_t *)packet_data_p = std::get(*it); - packet_data_p += sizeof(int32_t); - break; - case 'f': // std::holds_alternative(*it) - *(float *)packet_data_p = std::get(*it); - packet_data_p += sizeof(float); - break; - case 'S': // std::holds_alternative(*it) - str = std::get(*it); - if (str.size() > 64) - { - str.resize(64); - } - for (int i = str.size(); i < 64; ++i) - { - *(char *)(packet_data_p + i) = '\0'; - } - strncpy((char *)packet_data_p, str.c_str(), 64); - packet_data_p += 64; - break; - case 's': // std::holds_alternative(*it) - str = std::get(*it); - if (str.size() > 16) - { - str.resize(64); - } - for (int i = str.size(); i < 16; ++i) - { - *(char *)(packet_data_p + i) = '\0'; - } - strncpy((char *)packet_data_p, str.c_str(), str.size()); - packet_data_p += 16; - break; - case '?': // std::holds_alternative(*it) - case 'b': - *(bool *)packet_data_p = std::get(*it); - packet_data_p += sizeof(bool); - break; + switch (serialization_format[index_sf]) { + case 'i': // std::holds_alternative(*it) + *(int32_t *)packet_data_p = std::get(*it); + packet_data_p += sizeof(int32_t); + break; + case 'f': // std::holds_alternative(*it) + *(float *)packet_data_p = std::get(*it); + packet_data_p += sizeof(float); + break; + case 'S': // std::holds_alternative(*it) + str = std::get(*it); + if (str.size() > 64) { + str.resize(64); + } + for (int i = str.size(); i < 64; ++i) { + *(char *)(packet_data_p + i) = '\0'; + } + strncpy((char *)packet_data_p, str.c_str(), 64); + packet_data_p += 64; + break; + case 's': // std::holds_alternative(*it) + str = std::get(*it); + if (str.size() > 16) { + str.resize(64); + } + for (int i = str.size(); i < 16; ++i) { + *(char *)(packet_data_p + i) = '\0'; + } + strncpy((char *)packet_data_p, str.c_str(), str.size()); + packet_data_p += 16; + break; + case '?': // std::holds_alternative(*it) + case 'b': + *(bool *)packet_data_p = std::get(*it); + packet_data_p += sizeof(bool); + break; } ++it; ++index_sf; @@ -93,40 +90,45 @@ bool generate_data_frame(uint8_t *packet, const char *packet_description, const } bool generate_data_frame(uint8_t *packet, const char *packet_description, - std::vector &data) -{ + std::vector &data) { std::string serialization_format = get_serialization_format(data); - return generate_data_frame(packet, packet_description, serialization_format.c_str(), data); + return generate_data_frame(packet, packet_description, + serialization_format.c_str(), data); } /* Version 1 functions */ -void create_sensor_enviii_packet(uint8_t *packet, const char *module_name, int32_t pressure) -{ - *(uint16_t *)(packet + 0) = smart_device_protocol::Packet::PACKET_TYPE_SENSOR_ENV_III; +void create_sensor_enviii_packet(uint8_t *packet, const char *module_name, + int32_t pressure) { + *(uint16_t *)(packet + 0) = + smart_device_protocol::Packet::PACKET_TYPE_SENSOR_ENV_III; strncpy((char *)(packet + 2), module_name, 64); *(int32_t *)(packet + 2 + 64) = pressure; } -void create_sensor_stickv2_packet(uint8_t *packet, uint32_t number_of_person, const char *place_name) -{ - *(uint16_t *)(packet + 0) = smart_device_protocol::Packet::PACKET_TYPE_SENSOR_UNITV2_PERSON_COUNTER; +void create_sensor_stickv2_packet(uint8_t *packet, uint32_t number_of_person, + const char *place_name) { + *(uint16_t *)(packet + 0) = + smart_device_protocol::Packet::PACKET_TYPE_SENSOR_UNITV2_PERSON_COUNTER; *(uint32_t *)(packet + 2) = number_of_person; strncpy((char *)(packet + 2 + 4), place_name, 64); } -void create_device_message_board_meta_packet(uint8_t *packet, const char *module_name) -{ - *(uint16_t *)(packet + 0) = smart_device_protocol::Packet::PACKET_TYPE_DEVICE_MESSAGE_BOARD_META; +void create_device_message_board_meta_packet(uint8_t *packet, + const char *module_name) { + *(uint16_t *)(packet + 0) = + smart_device_protocol::Packet::PACKET_TYPE_DEVICE_MESSAGE_BOARD_META; strncpy((char *)(packet + 2), module_name, 64); } -void create_device_message_board_data_packet(uint8_t *packet, const char *source_name, uint64_t timeout_duration, - const char *message) -{ - *(uint16_t *)(packet + 0) = smart_device_protocol::Packet::PACKET_TYPE_DEVICE_MESSAGE_BOARD_DATA; +void create_device_message_board_data_packet(uint8_t *packet, + const char *source_name, + uint64_t timeout_duration, + const char *message) { + *(uint16_t *)(packet + 0) = + smart_device_protocol::Packet::PACKET_TYPE_DEVICE_MESSAGE_BOARD_DATA; strncpy((char *)(packet + 2), source_name, 64); *(uint64_t *)(packet + 2 + 64) = timeout_duration; strncpy((char *)(packet + 2 + 64 + 8), message, 64); } -#endif // SMART_DEVICE_PROTOCOL_PACKET_CREATOR_H__ \ No newline at end of file +#endif // SMART_DEVICE_PROTOCOL_PACKET_CREATOR_H__ \ No newline at end of file diff --git a/arduino_lib/sdp/packet_parser.h b/arduino_lib/sdp/packet_parser.h index 4943e996..1d15328c 100644 --- a/arduino_lib/sdp/packet_parser.h +++ b/arduino_lib/sdp/packet_parser.h @@ -1,82 +1,83 @@ #ifndef SMART_DEVICE_PROTOCOL_PACKET_PARSER_H__ #define SMART_DEVICE_PROTOCOL_PACKET_PARSER_H__ +#include #include + #include #include #include -#include - #include "sdp/packet_util.h" -uint16_t get_packet_type(const uint8_t *packet) -{ - return *(uint16_t *)packet; -} +uint16_t get_packet_type(const uint8_t *packet) { return *(uint16_t *)packet; } -SDPInterfaceDescription get_interface_definition(const uint8_t *packet) -{ +SDPInterfaceDescription get_interface_definition(const uint8_t *packet) { std::string packet_description = std::string((char *)(packet + 2), 64); std::string serialization_format = std::string((char *)(packet + 2 + 64), 10); - packet_description.erase(std::find(packet_description.begin(), packet_description.end(), '\0'), packet_description.end()); - serialization_format.erase(std::find(serialization_format.begin(), serialization_format.end(), '\0'), serialization_format.end()); + packet_description.erase( + std::find(packet_description.begin(), packet_description.end(), '\0'), + packet_description.end()); + serialization_format.erase( + std::find(serialization_format.begin(), serialization_format.end(), '\0'), + serialization_format.end()); return std::make_tuple(packet_description, serialization_format); } -std::tuple> parse_packet_as_meta_packet(const uint8_t *packet) -{ +std::tuple> +parse_packet_as_meta_packet(const uint8_t *packet) { std::string device_name; - std::vector packet_description_and_serialization_format; + std::vector + packet_description_and_serialization_format; device_name = std::string((char *)(packet + 2), 20); - for (int i = 0; i < 3; ++i) - { - std::string packet_description = std::string((char *)(packet + 2 + 20 + 74 * i), 64); - std::string serialization_format = std::string((char *)(packet + 2 + 20 + 74 * i + 64), 10); + for (int i = 0; i < 3; ++i) { + std::string packet_description = + std::string((char *)(packet + 2 + 20 + 74 * i), 64); + std::string serialization_format = + std::string((char *)(packet + 2 + 20 + 74 * i + 64), 10); // Remove '\0' characters from strings - packet_description.erase(std::find(packet_description.begin(), packet_description.end(), '\0'), packet_description.end()); - serialization_format.erase(std::find(serialization_format.begin(), serialization_format.end(), '\0'), serialization_format.end()); - packet_description_and_serialization_format.push_back(std::make_tuple(packet_description, serialization_format)); + packet_description.erase( + std::find(packet_description.begin(), packet_description.end(), '\0'), + packet_description.end()); + serialization_format.erase(std::find(serialization_format.begin(), + serialization_format.end(), '\0'), + serialization_format.end()); + packet_description_and_serialization_format.push_back( + std::make_tuple(packet_description, serialization_format)); } - return std::make_tuple(device_name, packet_description_and_serialization_format); + return std::make_tuple(device_name, + packet_description_and_serialization_format); } -std::tuple> parse_packet_as_data_packet(const uint8_t *packet) -{ - SDPInterfaceDescription packet_description_and_serialization_format = get_interface_definition(packet); - std::string serialization_format = std::get<1>(packet_description_and_serialization_format); +std::tuple> +parse_packet_as_data_packet(const uint8_t *packet) { + SDPInterfaceDescription packet_description_and_serialization_format = + get_interface_definition(packet); + std::string serialization_format = + std::get<1>(packet_description_and_serialization_format); std::vector data; auto packet_data_p = packet + 2 + 64 + 10; - for (int i = 0; i < serialization_format.size(); ++i) - { - if (serialization_format[i] == 'i') - { + for (int i = 0; i < serialization_format.size(); ++i) { + if (serialization_format[i] == 'i') { data.push_back(SDPData(*(int32_t *)packet_data_p)); packet_data_p += sizeof(int32_t); - } - else if (serialization_format[i] == 'f') - { + } else if (serialization_format[i] == 'f') { data.push_back(SDPData(*(float *)packet_data_p)); packet_data_p += sizeof(float); - } - else if (serialization_format[i] == 'S') - { + } else if (serialization_format[i] == 'S') { std::string str = std::string((char *)packet_data_p, 64); str.erase(std::find(str.begin(), str.end(), '\0'), str.end()); SDPData str_sdp = str; data.push_back(str_sdp); packet_data_p += 64; - } - else if (serialization_format[i] == 's') - { + } else if (serialization_format[i] == 's') { std::string str = std::string((char *)packet_data_p, 16); str.erase(std::find(str.begin(), str.end(), '\0'), str.end()); SDPData str_sdp = str; data.push_back(str_sdp); packet_data_p += 16; - } - else if (serialization_format[i] == '?' or serialization_format[i] == 'b') - { + } else if (serialization_format[i] == '?' or + serialization_format[i] == 'b') { data.push_back(SDPData(*(bool *)packet_data_p)); packet_data_p += sizeof(bool); } @@ -85,35 +86,38 @@ std::tuple> parse_packet_as_data_p } /* Version 1 functions */ -void parse_packet_as_test_packet(const uint8_t *packet, uint16_t &packet_type, int32_t &num_int, float num_float, - char *str) -{ +void parse_packet_as_test_packet(const uint8_t *packet, uint16_t &packet_type, + int32_t &num_int, float num_float, char *str) { packet_type = *(uint16_t *)packet; num_int = *(int32_t *)(packet + 2); num_float = *(float *)(packet + 2 + 4); strncpy(str, (char *)(packet + 2 + 4 + 4), 64); } -void parse_packet_as_named_string_packet(const uint8_t *packet, uint16_t &packet_type, char *name, char *value) -{ +void parse_packet_as_named_string_packet(const uint8_t *packet, + uint16_t &packet_type, char *name, + char *value) { packet_type = *(uint16_t *)packet; strncpy(name, (char *)(packet + 2), 64); strncpy(value, (char *)(packet + 2 + 64), 64); } -void parse_packet_as_message_board_meta_packet(const uint8_t *packet, uint16_t &packet_type, char *module_name) -{ +void parse_packet_as_message_board_meta_packet(const uint8_t *packet, + uint16_t &packet_type, + char *module_name) { packet_type = *(uint16_t *)packet; strncpy(module_name, (char *)(packet + 2), 64); } -void parse_packet_as_message_board_data_packet(const uint8_t *packet, uint16_t &packet_type, char *source_name, - uint64_t &timeout_duration, char *message) -{ +void parse_packet_as_message_board_data_packet(const uint8_t *packet, + uint16_t &packet_type, + char *source_name, + uint64_t &timeout_duration, + char *message) { packet_type = *(uint16_t *)packet; strncpy(source_name, (char *)(packet + 2), 64); timeout_duration = *(uint64_t *)(packet + 2 + 64); strncpy(message, (char *)(packet + 2 + 64 + 8), 64); } -#endif // SMART_DEVICE_PROTOCOL_PACKET_PARSER_H__z \ No newline at end of file +#endif // SMART_DEVICE_PROTOCOL_PACKET_PARSER_H__z \ No newline at end of file diff --git a/arduino_lib/sdp/packet_util.h b/arduino_lib/sdp/packet_util.h index 58c9f214..3c2c4e0b 100644 --- a/arduino_lib/sdp/packet_util.h +++ b/arduino_lib/sdp/packet_util.h @@ -7,83 +7,64 @@ typedef std::variant SDPData; typedef std::tuple SDPInterfaceDescription; -std::string get_serialization_format(const std::vector &data) -{ - std::string serialization_format; - for (auto itr = data.begin(); itr != data.end(); ++itr) - { - if (std::holds_alternative(*itr)) - { - serialization_format += "i"; +std::string get_serialization_format(const std::vector &data) { + std::string serialization_format; + for (auto itr = data.begin(); itr != data.end(); ++itr) { + if (std::holds_alternative(*itr)) { + serialization_format += "i"; + } else if (std::holds_alternative(*itr)) { + serialization_format += "f"; + } else if (std::holds_alternative(*itr)) { + if (std::get(*itr).size() > 16) { + serialization_format += "S"; + } else { + serialization_format += "s"; + } + } else if (std::holds_alternative(*itr)) { + serialization_format += "?"; + } + } + return serialization_format; +} + +bool is_consistent_serialization_format(const std::string &serialization_format, + const std::vector &data) { + if (serialization_format.size() != std::vector(data).size()) { + return false; + } + auto itr = data.begin(); + int index_sf = 0; + while (itr != data.end()) { + switch (serialization_format[index_sf]) { + case 'i': + if (not std::holds_alternative(*itr)) { + return false; } - else if (std::holds_alternative(*itr)) - { - serialization_format += "f"; + break; + case 'f': + if (not std::holds_alternative(*itr)) { + return false; } - else if (std::holds_alternative(*itr)) - { - if (std::get(*itr).size() > 16) - { - serialization_format += "S"; - } - else - { - serialization_format += "s"; - } + break; + case 'S': + case 's': + if (not std::holds_alternative(*itr)) { + return false; } - else if (std::holds_alternative(*itr)) - { - serialization_format += "?"; + break; + case '?': + case 'b': + if (not std::holds_alternative(*itr)) { + return false; } - } - return serialization_format; -} - -bool is_consistent_serialization_format(const std::string &serialization_format, const std::vector &data) -{ - if (serialization_format.size() != std::vector(data).size()) - { + break; + default: return false; } - auto itr = data.begin(); - int index_sf = 0; - while (itr != data.end()) - { - switch (serialization_format[index_sf]) - { - case 'i': - if (not std::holds_alternative(*itr)) - { - return false; - } - break; - case 'f': - if (not std::holds_alternative(*itr)) - { - return false; - } - break; - case 'S': - case 's': - if (not std::holds_alternative(*itr)) - { - return false; - } - break; - case '?': - case 'b': - if (not std::holds_alternative(*itr)) - { - return false; - } - break; - default: - return false; - } - itr++; - index_sf; - } - return true; + itr++; + index_sf; + } + return true; } -#endif // SMART_DEVICE_PROTOCOL_PACKET_UTIL_H__ \ No newline at end of file +#endif // SMART_DEVICE_PROTOCOL_PACKET_UTIL_H__ \ No newline at end of file diff --git a/arduino_lib/sdp/sdp.h b/arduino_lib/sdp/sdp.h index c7106e3e..f39b1c74 100644 --- a/arduino_lib/sdp/sdp.h +++ b/arduino_lib/sdp/sdp.h @@ -7,22 +7,26 @@ * - smart_device_protocol/Packet.h */ -#include -#include #include - +#include +#include #include #include "sdp/esp_now.h" #include "sdp/packet_creator.h" #include "sdp/packet_parser.h" -typedef void (*sdp_data_if_recv_cb_t)(const uint8_t *mac_addr, const std::vector &body); -typedef void (*sdp_data_recv_cb_t)(const uint8_t *mac_addr, const SDPInterfaceDescription &interface_description, - const std::vector &body); -typedef void (*sdp_meta_recv_cb_t)(const uint8_t *mac_addr, const std::string &device_name, - const std::vector &interfaces); -typedef std::tuple SDPInterfaceCallbackEntry; +typedef void (*sdp_data_if_recv_cb_t)(const uint8_t *mac_addr, + const std::vector &body); +typedef void (*sdp_data_recv_cb_t)( + const uint8_t *mac_addr, + const SDPInterfaceDescription &interface_description, + const std::vector &body); +typedef void (*sdp_meta_recv_cb_t)( + const uint8_t *mac_addr, const std::string &device_name, + const std::vector &interfaces); +typedef std::tuple + SDPInterfaceCallbackEntry; // Internal variables inline String _sdp_device_name; @@ -33,323 +37,295 @@ inline std::vector _esp_now_recv_callbacks; // Internal variables for get_sdp_interfaces() // Each element stands for mac_addr, device_name, interfaces -inline std::vector>> _vector_device_interfaces; +inline std::vector< + std::tuple>> + _vector_device_interfaces; // Function declarations -bool _broadcast_sdp_meta_packet(const SDPInterfaceDescription &packet_description_and_serialization_format); +bool _broadcast_sdp_meta_packet( + const SDPInterfaceDescription &packet_description_and_serialization_format); void _meta_frame_broadcast_task(void *parameter); void _OnDataRecv(const uint8_t *mac_addr, const uint8_t *data, int data_len); -void _get_device_interfaces_callback(const uint8_t *mac_addr, const std::string &device_name, - const std::vector &interfaces); -esp_err_t send_sdp_esp_now_packet(const uint8_t *peer_addr, uint8_t *data, int data_len); +void _get_device_interfaces_callback( + const uint8_t *mac_addr, const std::string &device_name, + const std::vector &interfaces); +esp_err_t send_sdp_esp_now_packet(const uint8_t *peer_addr, uint8_t *data, + int data_len); esp_err_t broadcast_sdp_esp_now_packet(uint8_t *data, int data_len); -std::string _convert_mac_address(const uint8_t *mac_addr) -{ - if (mac_addr == NULL) - { - return ""; - } - else - { - String addr = String(mac_addr[0], 16) + ":" + - String(mac_addr[1], 16) + ":" + - String(mac_addr[2], 16) + ":" + - String(mac_addr[3], 16) + ":" + - String(mac_addr[4], 16) + ":" + - String(mac_addr[5], 16); - return addr.c_str(); - } +std::string _convert_mac_address(const uint8_t *mac_addr) { + if (mac_addr == NULL) { + return ""; + } else { + String addr = String(mac_addr[0], 16) + ":" + String(mac_addr[1], 16) + + ":" + String(mac_addr[2], 16) + ":" + + String(mac_addr[3], 16) + ":" + String(mac_addr[4], 16) + + ":" + String(mac_addr[5], 16); + return addr.c_str(); + } } -void _OnDataRecv(const uint8_t *mac_addr, const uint8_t *data, int data_len) -{ - uint8_t packet_type = get_packet_type(data); - for (auto &entry : _esp_now_recv_callbacks) - { - entry(mac_addr, data, data_len); - } - if (packet_type == smart_device_protocol::Packet::PACKET_TYPE_DATA) - { - auto packet = parse_packet_as_data_packet(data); - SDPInterfaceDescription packet_description_and_serialization_format = std::get<0>(packet); - std::string packet_description = std::get<0>(packet_description_and_serialization_format); - std::string serialization_format = std::get<1>(packet_description_and_serialization_format); - std::vector body = std::get<1>(packet); +void _OnDataRecv(const uint8_t *mac_addr, const uint8_t *data, int data_len) { + uint8_t packet_type = get_packet_type(data); + for (auto &entry : _esp_now_recv_callbacks) { + entry(mac_addr, data, data_len); + } + if (packet_type == smart_device_protocol::Packet::PACKET_TYPE_DATA) { + auto packet = parse_packet_as_data_packet(data); + SDPInterfaceDescription packet_description_and_serialization_format = + std::get<0>(packet); + std::string packet_description = + std::get<0>(packet_description_and_serialization_format); + std::string serialization_format = + std::get<1>(packet_description_and_serialization_format); + std::vector body = std::get<1>(packet); - for (auto &entry : _sdp_data_callbacks) - { - entry(mac_addr, packet_description_and_serialization_format, body); - } + for (auto &entry : _sdp_data_callbacks) { + entry(mac_addr, packet_description_and_serialization_format, body); + } - for (auto &entry : _sdp_interface_data_callbacks) - { - if (packet_description == std::get<0>(std::get<0>(entry)) and - serialization_format == std::get<1>(std::get<0>(entry))) - { - std::get<1>(entry)(mac_addr, body); - } - } + for (auto &entry : _sdp_interface_data_callbacks) { + if (packet_description == std::get<0>(std::get<0>(entry)) and + serialization_format == std::get<1>(std::get<0>(entry))) { + std::get<1>(entry)(mac_addr, body); + } } - else if (packet_type == smart_device_protocol::Packet::PACKET_TYPE_META) - { - auto packet = parse_packet_as_meta_packet(data); - std::string device_name = std::get<0>(packet); - std::vector interfaces = std::get<1>(packet); + } else if (packet_type == smart_device_protocol::Packet::PACKET_TYPE_META) { + auto packet = parse_packet_as_meta_packet(data); + std::string device_name = std::get<0>(packet); + std::vector interfaces = std::get<1>(packet); - for (auto &entry : _sdp_meta_callbacks) - { - entry(mac_addr, device_name, interfaces); - } + for (auto &entry : _sdp_meta_callbacks) { + entry(mac_addr, device_name, interfaces); } + } } -bool _broadcast_sdp_meta_packet(const SDPInterfaceDescription &packet_description_and_serialization_format) -{ - uint8_t buf[245]; - const std::string &packet_description = std::get<0>(packet_description_and_serialization_format); - const std::string &serialization_format = std::get<1>(packet_description_and_serialization_format); - generate_meta_frame(buf, _sdp_device_name.c_str(), packet_description.c_str(), serialization_format.c_str(), "", "", - "", ""); - bool success = broadcast_sdp_esp_now_packet(buf, sizeof(buf)) == ESP_OK; - return success; +bool _broadcast_sdp_meta_packet( + const SDPInterfaceDescription + &packet_description_and_serialization_format) { + uint8_t buf[245]; + const std::string &packet_description = + std::get<0>(packet_description_and_serialization_format); + const std::string &serialization_format = + std::get<1>(packet_description_and_serialization_format); + generate_meta_frame(buf, _sdp_device_name.c_str(), packet_description.c_str(), + serialization_format.c_str(), "", "", "", ""); + bool success = broadcast_sdp_esp_now_packet(buf, sizeof(buf)) == ESP_OK; + return success; } -void _meta_frame_broadcast_task(void *parameter) -{ - for (;;) - { - vTaskDelay(pdMS_TO_TICKS(1000)); - for (auto &entry : _sdp_interface_data_callbacks) - { - const SDPInterfaceDescription &packet_description_and_serialization_format = std::get<0>(entry); - _broadcast_sdp_meta_packet(packet_description_and_serialization_format); - } - if (_sdp_interface_data_callbacks.size() == 0) - { - _broadcast_sdp_meta_packet(std::make_tuple("", "")); - } +void _meta_frame_broadcast_task(void *parameter) { + for (;;) { + vTaskDelay(pdMS_TO_TICKS(1000)); + for (auto &entry : _sdp_interface_data_callbacks) { + const SDPInterfaceDescription + &packet_description_and_serialization_format = std::get<0>(entry); + _broadcast_sdp_meta_packet(packet_description_and_serialization_format); } + if (_sdp_interface_data_callbacks.size() == 0) { + _broadcast_sdp_meta_packet(std::make_tuple("", "")); + } + } } -bool init_sdp(uint8_t *mac_address, const String &device_name) -{ - if (mac_address != NULL) - { - esp_read_mac(mac_address, ESP_MAC_WIFI_STA); - } - _sdp_device_name = device_name; - WiFi.mode(WIFI_STA); - WiFi.disconnect(); - if (not esp_now_init() == ESP_OK) - { - return false; - } - xTaskCreate(_meta_frame_broadcast_task, "meta_frame_broadcast_task", 16384, NULL, 1, NULL); - esp_now_register_recv_cb(_OnDataRecv); - return true; +bool init_sdp(uint8_t *mac_address, const String &device_name) { + if (mac_address != NULL) { + esp_read_mac(mac_address, ESP_MAC_WIFI_STA); + } + _sdp_device_name = device_name; + WiFi.mode(WIFI_STA); + WiFi.disconnect(); + if (not esp_now_init() == ESP_OK) { + return false; + } + xTaskCreate(_meta_frame_broadcast_task, "meta_frame_broadcast_task", 16384, + NULL, 1, NULL); + esp_now_register_recv_cb(_OnDataRecv); + return true; } -bool register_sdp_interface_callback(SDPInterfaceDescription packet_description_and_serialization_format, - sdp_data_if_recv_cb_t callback) -{ - // Check if the callback is already registered - for (auto &entry : _sdp_interface_data_callbacks) - { - if (std::get<0>(std::get<0>(entry)) == std::get<0>(packet_description_and_serialization_format) and - std::get<1>(std::get<0>(entry)) == std::get<1>(packet_description_and_serialization_format)) - { - return false; - } +bool register_sdp_interface_callback( + SDPInterfaceDescription packet_description_and_serialization_format, + sdp_data_if_recv_cb_t callback) { + // Check if the callback is already registered + for (auto &entry : _sdp_interface_data_callbacks) { + if (std::get<0>(std::get<0>(entry)) == + std::get<0>(packet_description_and_serialization_format) and + std::get<1>(std::get<0>(entry)) == + std::get<1>(packet_description_and_serialization_format)) { + return false; } - _sdp_interface_data_callbacks.push_back(std::make_tuple(packet_description_and_serialization_format, callback)); - return true; + } + _sdp_interface_data_callbacks.push_back( + std::make_tuple(packet_description_and_serialization_format, callback)); + return true; } -bool unregister_sdp_interface_callback(SDPInterfaceDescription packet_description_and_serialization_format) -{ - for (auto it = _sdp_interface_data_callbacks.begin(); it != _sdp_interface_data_callbacks.end(); ++it) - { - if (std::get<0>(std::get<0>(*it)) == std::get<0>(packet_description_and_serialization_format) and - std::get<1>(std::get<0>(*it)) == std::get<1>(packet_description_and_serialization_format)) - { - _sdp_interface_data_callbacks.erase(it); - return true; - } +bool unregister_sdp_interface_callback( + SDPInterfaceDescription packet_description_and_serialization_format) { + for (auto it = _sdp_interface_data_callbacks.begin(); + it != _sdp_interface_data_callbacks.end(); ++it) { + if (std::get<0>(std::get<0>(*it)) == + std::get<0>(packet_description_and_serialization_format) and + std::get<1>(std::get<0>(*it)) == + std::get<1>(packet_description_and_serialization_format)) { + _sdp_interface_data_callbacks.erase(it); + return true; } - return false; + } + return false; } -bool register_sdp_data_callback(sdp_data_recv_cb_t callback) -{ - _sdp_data_callbacks.push_back(callback); - return true; +bool register_sdp_data_callback(sdp_data_recv_cb_t callback) { + _sdp_data_callbacks.push_back(callback); + return true; } -bool unregister_sdp_data_callback(sdp_data_recv_cb_t callback) -{ - for (auto it = _sdp_data_callbacks.begin(); it != _sdp_data_callbacks.end(); ++it) - { - if (*it == callback) - { - _sdp_data_callbacks.erase(it); - return true; - } +bool unregister_sdp_data_callback(sdp_data_recv_cb_t callback) { + for (auto it = _sdp_data_callbacks.begin(); it != _sdp_data_callbacks.end(); + ++it) { + if (*it == callback) { + _sdp_data_callbacks.erase(it); + return true; } - return false; + } + return false; } -bool register_sdp_meta_callback(sdp_meta_recv_cb_t callback) -{ - _sdp_meta_callbacks.push_back(callback); - return true; +bool register_sdp_meta_callback(sdp_meta_recv_cb_t callback) { + _sdp_meta_callbacks.push_back(callback); + return true; } -bool unregister_sdp_meta_callback(sdp_meta_recv_cb_t callback) -{ - for (auto it = _sdp_meta_callbacks.begin(); it != _sdp_meta_callbacks.end(); ++it) - { - if (*it == callback) - { - _sdp_meta_callbacks.erase(it); - return true; - } +bool unregister_sdp_meta_callback(sdp_meta_recv_cb_t callback) { + for (auto it = _sdp_meta_callbacks.begin(); it != _sdp_meta_callbacks.end(); + ++it) { + if (*it == callback) { + _sdp_meta_callbacks.erase(it); + return true; } - return false; + } + return false; } -bool register_sdp_esp_now_recv_callback(esp_now_recv_cb_t callback) -{ - _esp_now_recv_callbacks.push_back(callback); - return true; +bool register_sdp_esp_now_recv_callback(esp_now_recv_cb_t callback) { + _esp_now_recv_callbacks.push_back(callback); + return true; } -bool unregister_sdp_esp_now_recv_callback(esp_now_recv_cb_t callback) -{ - for (auto it = _esp_now_recv_callbacks.begin(); it != _esp_now_recv_callbacks.end(); ++it) - { - if (*it == callback) - { - _esp_now_recv_callbacks.erase(it); - return true; - } +bool unregister_sdp_esp_now_recv_callback(esp_now_recv_cb_t callback) { + for (auto it = _esp_now_recv_callbacks.begin(); + it != _esp_now_recv_callbacks.end(); ++it) { + if (*it == callback) { + _esp_now_recv_callbacks.erase(it); + return true; } - return false; + } + return false; } -bool send_sdp_data_packet(std::string &packet_description, std::vector &body) -{ - uint8_t buf[240]; - bool ret = generate_data_frame(buf, packet_description.c_str(), body); - if (not ret) - { - return false; - } - else - { - return broadcast_sdp_esp_now_packet(buf, sizeof(buf)) == ESP_OK; - } +bool send_sdp_data_packet(std::string &packet_description, + std::vector &body) { + uint8_t buf[240]; + bool ret = generate_data_frame(buf, packet_description.c_str(), body); + if (not ret) { + return false; + } else { + return broadcast_sdp_esp_now_packet(buf, sizeof(buf)) == ESP_OK; + } } -bool send_sdp_data_packet(const SDPInterfaceDescription &interface_description, std::vector &body) -{ - uint8_t buf[240]; - const std::string &packet_description = std::get<0>(interface_description); - const std::string &serialization_format = std::get<1>(interface_description); - bool ret = generate_data_frame(buf, packet_description.c_str(), serialization_format.c_str(), body); - if (not ret) - { - return false; - } - else - { - return broadcast_sdp_esp_now_packet(buf, sizeof(buf)) == ESP_OK; - } +bool send_sdp_data_packet(const SDPInterfaceDescription &interface_description, + std::vector &body) { + uint8_t buf[240]; + const std::string &packet_description = std::get<0>(interface_description); + const std::string &serialization_format = std::get<1>(interface_description); + bool ret = generate_data_frame(buf, packet_description.c_str(), + serialization_format.c_str(), body); + if (not ret) { + return false; + } else { + return broadcast_sdp_esp_now_packet(buf, sizeof(buf)) == ESP_OK; + } } -esp_err_t send_sdp_esp_now_packet(const uint8_t *peer_addr, uint8_t *data, int data_len) -{ - esp_now_peer_info_t peer_info; - memset(&peer_info, 0, sizeof(peer_info)); - for (int i = 0; i < 6; i++) - { - peer_info.peer_addr[i] = peer_addr[i]; - } - esp_err_t addStatus = esp_now_add_peer(&peer_info); - if (addStatus != ESP_OK) - { - return addStatus; - } - esp_err_t result = esp_now_send(peer_addr, data, data_len); - esp_now_del_peer(peer_addr); - return result; +esp_err_t send_sdp_esp_now_packet(const uint8_t *peer_addr, uint8_t *data, + int data_len) { + esp_now_peer_info_t peer_info; + memset(&peer_info, 0, sizeof(peer_info)); + for (int i = 0; i < 6; i++) { + peer_info.peer_addr[i] = peer_addr[i]; + } + esp_err_t addStatus = esp_now_add_peer(&peer_info); + if (addStatus != ESP_OK) { + return addStatus; + } + esp_err_t result = esp_now_send(peer_addr, data, data_len); + esp_now_del_peer(peer_addr); + return result; } -esp_err_t broadcast_sdp_esp_now_packet(uint8_t *data, int data_len) -{ - const uint8_t broadcast_address[6] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; - return send_sdp_esp_now_packet(broadcast_address, data, data_len); +esp_err_t broadcast_sdp_esp_now_packet(uint8_t *data, int data_len) { + const uint8_t broadcast_address[6] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; + return send_sdp_esp_now_packet(broadcast_address, data, data_len); } // Retrive device interfaces from meta package for given duration -const std::vector>> &get_sdp_interfaces(unsigned long duration = 3000) -{ - _vector_device_interfaces.clear(); - unsigned long start_time = millis(); - register_sdp_meta_callback(_get_device_interfaces_callback); - while (millis() - start_time < duration) - { - vTaskDelay(pdMS_TO_TICKS(100)); - } - unregister_sdp_meta_callback(_get_device_interfaces_callback); - return _vector_device_interfaces; +const std::vector>> & +get_sdp_interfaces(unsigned long duration = 3000) { + _vector_device_interfaces.clear(); + unsigned long start_time = millis(); + register_sdp_meta_callback(_get_device_interfaces_callback); + while (millis() - start_time < duration) { + vTaskDelay(pdMS_TO_TICKS(100)); + } + unregister_sdp_meta_callback(_get_device_interfaces_callback); + return _vector_device_interfaces; } // Call back function for get_device_interfaces() to store MetaFrame -void _get_device_interfaces_callback(const uint8_t *mac_addr, const std::string &device_name, - const std::vector &interfaces) -{ - std::string address = _convert_mac_address(mac_addr); +void _get_device_interfaces_callback( + const uint8_t *mac_addr, const std::string &device_name, + const std::vector &interfaces) { + std::string address = _convert_mac_address(mac_addr); - // if _vector_device_interfaces has not entry for address, add interfaces to it - for (auto &entry : _vector_device_interfaces) - { - if (std::get<0>(entry) == address) - { - for (auto &interface : interfaces) - { - // Add only if interface is not empty - if (std::get<0>(interface).size() > 0 and std::get<1>(interface).size() > 0) - { - // Add only there is no same interface - bool ok = true; - for (auto &original_interface : std::get<2>(entry)) - { - if (std::get<0>(original_interface) == std::get<0>(interface) and - std::get<1>(original_interface) == std::get<1>(interface)) - { - ok = false; - break; - } - } - if (ok) - { - std::get<2>(entry).push_back(interface); - } - } + // if _vector_device_interfaces has not entry for address, add interfaces to + // it + for (auto &entry : _vector_device_interfaces) { + if (std::get<0>(entry) == address) { + for (auto &interface : interfaces) { + // Add only if interface is not empty + if (std::get<0>(interface).size() > 0 and + std::get<1>(interface).size() > 0) { + // Add only there is no same interface + bool ok = true; + for (auto &original_interface : std::get<2>(entry)) { + if (std::get<0>(original_interface) == std::get<0>(interface) and + std::get<1>(original_interface) == std::get<1>(interface)) { + ok = false; + break; } - return; + } + if (ok) { + std::get<2>(entry).push_back(interface); + } } + } + return; } - // add interface which is not empty - std::vector valid_interfaces; - for (auto &interface : interfaces) - { - if (std::get<0>(interface).size() > 0 and std::get<1>(interface).size() > 0) - { - valid_interfaces.push_back(std::make_tuple(std::get<0>(interface), std::get<1>(interface))); - } + } + // add interface which is not empty + std::vector valid_interfaces; + for (auto &interface : interfaces) { + if (std::get<0>(interface).size() > 0 and + std::get<1>(interface).size() > 0) { + valid_interfaces.push_back( + std::make_tuple(std::get<0>(interface), std::get<1>(interface))); } - _vector_device_interfaces.push_back(std::make_tuple(address, device_name, valid_interfaces)); - return; + } + _vector_device_interfaces.push_back( + std::make_tuple(address, device_name, valid_interfaces)); + return; } diff --git a/arduino_lib/sdp/sdp_util.h b/arduino_lib/sdp/sdp_util.h index 4789923e..e1d705a9 100644 --- a/arduino_lib/sdp/sdp_util.h +++ b/arduino_lib/sdp/sdp_util.h @@ -3,4 +3,4 @@ #include "sdp/sdp.h" -#endif // SMART_DEVICE_PROTOCOL_SDP_UTIL_H +#endif // SMART_DEVICE_PROTOCOL_SDP_UTIL_H diff --git a/arduino_lib/utils/config_loader.h b/arduino_lib/utils/config_loader.h index 2f43aa78..0703fb6a 100644 --- a/arduino_lib/utils/config_loader.h +++ b/arduino_lib/utils/config_loader.h @@ -5,24 +5,22 @@ #include template -bool load_json_from_FS(fs::FS &fs, const String &filename, StaticJsonDocument &doc) -{ - auto file = fs.open(filename.c_str()); - if (!file) - { - Serial.printf("Failed to open config file from %s\n", filename.c_str()); - file.close(); - return false; - } - DeserializationError error = deserializeJson(doc, file.readString()); - if (error) - { - Serial.println("Failed to parse config file"); - file.close(); - return false; - } +bool load_json_from_FS(fs::FS &fs, const String &filename, + StaticJsonDocument &doc) { + auto file = fs.open(filename.c_str()); + if (!file) { + Serial.printf("Failed to open config file from %s\n", filename.c_str()); file.close(); - return true; + return false; + } + DeserializationError error = deserializeJson(doc, file.readString()); + if (error) { + Serial.println("Failed to parse config file"); + file.close(); + return false; + } + file.close(); + return true; } -#endif // SMART_DEVICE_PROTOCOL_CONFIG_LOADER_H \ No newline at end of file +#endif // SMART_DEVICE_PROTOCOL_CONFIG_LOADER_H \ No newline at end of file diff --git a/arduino_lib/web_services/sesami_util.h b/arduino_lib/web_services/sesami_util.h index b7852e44..7cc955be 100644 --- a/arduino_lib/web_services/sesami_util.h +++ b/arduino_lib/web_services/sesami_util.h @@ -1,182 +1,159 @@ #ifndef SESAMI_UTIL_H #define SESAMI_UTIL_H +#include +#include +#include #include #include #include -#include - -#include -#include - #include #include String generateRandomTag(String secret_key, uint32_t date_sec); -std::optional operation_sesami(String device_uuid, String api_key, int command, String secret_key); +std::optional operation_sesami(String device_uuid, String api_key, + int command, String secret_key); std::optional get_sesami_status(String device_uuid, String api_key); std::optional get_sesami_history(String device_uuid, String api_key); -String generateRandomTag(String secret_key, uint32_t date_sec) -{ - AESTiny128 aes128; - AES_CMAC cmac(aes128); - - uint8_t dateBytes[3]; - dateBytes[0] = (date_sec >> 8) & 0xFF; - dateBytes[1] = (date_sec >> 16) & 0xFF; - dateBytes[2] = (date_sec >> 24) & 0xFF; - - uint8_t key[16]; - for (int i = 0; i < 16; i++) - { - key[i] = 0; - if (secret_key[2 * i] >= '0' and secret_key[2 * i] <= '9') - { - key[i] += (secret_key[2 * i] - '0') << 4; - } - else if (secret_key[2 * i] >= 'a' and secret_key[2 * i] <= 'f') - { - key[i] += (secret_key[2 * i] - 'a' + 10) << 4; - } - else if (secret_key[2 * i] >= 'A' and secret_key[2 * i] <= 'F') - { - key[i] += (secret_key[2 * i] - 'A' + 10) << 4; - } - else - { - USBSerial.printf("secret_key[%d]: %c\n", 2 * i, secret_key[2 * i]); - USBSerial.println("secret_key error!"); - } - - if (secret_key[2 * i + 1] >= '0' and secret_key[2 * i + 1] <= '9') - { - key[i] += (secret_key[2 * i + 1] - '0'); - } - else if (secret_key[2 * i + 1] >= 'a' and secret_key[2 * i + 1] <= 'f') - { - key[i] += (secret_key[2 * i + 1] - 'a' + 10); - } - else if (secret_key[2 * i + 1] >= 'A' and secret_key[2 * i + 1] <= 'F') - { - key[i] += (secret_key[2 * i + 1] - 'A' + 10); - } - else - { - USBSerial.printf("secret_key[%d]: %c\n", 2 * i + 1, secret_key[2 * i + 1]); - USBSerial.println("secret_key error!"); - } - } - - uint8_t output[16]; - - cmac.generateMAC(output, key, dateBytes, sizeof(dateBytes)); - - char outputHex[32]; - for (int i = 0; i < 16; i++) - { - sprintf(outputHex + (i * 2), "%02x", output[i]); - } - return String(outputHex); -} - -std::optional operation_sesami(String device_uuid, String api_key, int command, String secret_key) -{ - uint32_t date_sec = time(nullptr); - String sign = generateRandomTag(secret_key, date_sec); - String history = "test02"; - String base64History = base64::encode(history); - String body = String("{\"cmd\":") + command + String(",\"sign\":\"") + sign + String("\",\"history\":\"") + - base64History + String("\"}"); - String url = String("https://app.candyhouse.co/api/sesame2/") + device_uuid + String("/cmd"); - - HTTPClient http; - - if (!http.begin(url)) - { - return std::nullopt; +String generateRandomTag(String secret_key, uint32_t date_sec) { + AESTiny128 aes128; + AES_CMAC cmac(aes128); + + uint8_t dateBytes[3]; + dateBytes[0] = (date_sec >> 8) & 0xFF; + dateBytes[1] = (date_sec >> 16) & 0xFF; + dateBytes[2] = (date_sec >> 24) & 0xFF; + + uint8_t key[16]; + for (int i = 0; i < 16; i++) { + key[i] = 0; + if (secret_key[2 * i] >= '0' and secret_key[2 * i] <= '9') { + key[i] += (secret_key[2 * i] - '0') << 4; + } else if (secret_key[2 * i] >= 'a' and secret_key[2 * i] <= 'f') { + key[i] += (secret_key[2 * i] - 'a' + 10) << 4; + } else if (secret_key[2 * i] >= 'A' and secret_key[2 * i] <= 'F') { + key[i] += (secret_key[2 * i] - 'A' + 10) << 4; + } else { + USBSerial.printf("secret_key[%d]: %c\n", 2 * i, secret_key[2 * i]); + USBSerial.println("secret_key error!"); } - USBSerial.println("=== HTTPClient begin! ==="); - USBSerial.printf("URL: %s\n", url.c_str()); - USBSerial.printf("date: %d\n", date_sec); - USBSerial.printf("sign: %s\n", sign.c_str()); - USBSerial.printf("request body: %s\n", body.c_str()); - http.addHeader("Content-Type", "application/json"); - http.addHeader("x-api-key", api_key); - int responseCode = http.POST(body); - String result_body = http.getString(); - http.end(); - USBSerial.printf("** POST result **\n"); - USBSerial.printf("responseCode: %d\n", responseCode); - USBSerial.println("result_body: " + result_body); - - if (responseCode != 200) - { - return std::nullopt; + if (secret_key[2 * i + 1] >= '0' and secret_key[2 * i + 1] <= '9') { + key[i] += (secret_key[2 * i + 1] - '0'); + } else if (secret_key[2 * i + 1] >= 'a' and secret_key[2 * i + 1] <= 'f') { + key[i] += (secret_key[2 * i + 1] - 'a' + 10); + } else if (secret_key[2 * i + 1] >= 'A' and secret_key[2 * i + 1] <= 'F') { + key[i] += (secret_key[2 * i + 1] - 'A' + 10); + } else { + USBSerial.printf("secret_key[%d]: %c\n", 2 * i + 1, + secret_key[2 * i + 1]); + USBSerial.println("secret_key error!"); } - else - { - body.replace("\\\"", "\""); - USBSerial.println("body: " + result_body); - return result_body; - } -} + } -std::optional get_sesami_status(String device_uuid, String api_key) -{ - HTTPClient http; + uint8_t output[16]; - String url = String("https://app.candyhouse.co/api/sesame2/") + device_uuid; + cmac.generateMAC(output, key, dateBytes, sizeof(dateBytes)); - if (!http.begin(url)) - { - return std::nullopt; - } + char outputHex[32]; + for (int i = 0; i < 16; i++) { + sprintf(outputHex + (i * 2), "%02x", output[i]); + } + return String(outputHex); +} - USBSerial.println("=== HTTPClient begin! ==="); - USBSerial.printf("URL: %s\n", url.c_str()); - http.addHeader("Content-Type", "application/json"); - http.addHeader("x-api-key", api_key); - int responseCode = http.GET(); - String body = http.getString(); - USBSerial.printf("** GET status result **\n"); - USBSerial.printf("responseCode: %d\n", responseCode); +std::optional operation_sesami(String device_uuid, String api_key, + int command, String secret_key) { + uint32_t date_sec = time(nullptr); + String sign = generateRandomTag(secret_key, date_sec); + String history = "test02"; + String base64History = base64::encode(history); + String body = String("{\"cmd\":") + command + String(",\"sign\":\"") + sign + + String("\",\"history\":\"") + base64History + String("\"}"); + String url = String("https://app.candyhouse.co/api/sesame2/") + device_uuid + + String("/cmd"); + + HTTPClient http; + + if (!http.begin(url)) { + return std::nullopt; + } + + USBSerial.println("=== HTTPClient begin! ==="); + USBSerial.printf("URL: %s\n", url.c_str()); + USBSerial.printf("date: %d\n", date_sec); + USBSerial.printf("sign: %s\n", sign.c_str()); + USBSerial.printf("request body: %s\n", body.c_str()); + http.addHeader("Content-Type", "application/json"); + http.addHeader("x-api-key", api_key); + int responseCode = http.POST(body); + String result_body = http.getString(); + http.end(); + USBSerial.printf("** POST result **\n"); + USBSerial.printf("responseCode: %d\n", responseCode); + USBSerial.println("result_body: " + result_body); + + if (responseCode != 200) { + return std::nullopt; + } else { body.replace("\\\"", "\""); - USBSerial.println("body: " + body); - http.end(); - - return body; + USBSerial.println("body: " + result_body); + return result_body; + } } -std::optional get_sesami_history(String device_uuid, String api_key) -{ - HTTPClient http; +std::optional get_sesami_status(String device_uuid, String api_key) { + HTTPClient http; - String url = String("https://app.candyhouse.co/api/sesame2/") + device_uuid + String("/history?page=0&lg=5"); + String url = String("https://app.candyhouse.co/api/sesame2/") + device_uuid; - if (!http.begin(url)) - { - return std::nullopt; - } + if (!http.begin(url)) { + return std::nullopt; + } - USBSerial.println("=== HTTPClient begin! ==="); - USBSerial.printf("URL: %s\n", url.c_str()); - http.addHeader("Content-Type", "application/json"); - http.addHeader("x-api-key", api_key); - int responseCode = http.GET(); - String body = http.getString(); - USBSerial.printf("** GET history result **\n"); - USBSerial.printf("responseCode: %d\n", responseCode); - body.replace("\\\"", "\""); - USBSerial.println("body: " + body); - http.end(); + USBSerial.println("=== HTTPClient begin! ==="); + USBSerial.printf("URL: %s\n", url.c_str()); + http.addHeader("Content-Type", "application/json"); + http.addHeader("x-api-key", api_key); + int responseCode = http.GET(); + String body = http.getString(); + USBSerial.printf("** GET status result **\n"); + USBSerial.printf("responseCode: %d\n", responseCode); + body.replace("\\\"", "\""); + USBSerial.println("body: " + body); + http.end(); + + return body; +} - return body; +std::optional get_sesami_history(String device_uuid, String api_key) { + HTTPClient http; + + String url = String("https://app.candyhouse.co/api/sesame2/") + device_uuid + + String("/history?page=0&lg=5"); + + if (!http.begin(url)) { + return std::nullopt; + } + + USBSerial.println("=== HTTPClient begin! ==="); + USBSerial.printf("URL: %s\n", url.c_str()); + http.addHeader("Content-Type", "application/json"); + http.addHeader("x-api-key", api_key); + int responseCode = http.GET(); + String body = http.getString(); + USBSerial.printf("** GET history result **\n"); + USBSerial.printf("responseCode: %d\n", responseCode); + body.replace("\\\"", "\""); + USBSerial.println("body: " + body); + http.end(); + + return body; } -#endif // SESAMI_UTIL_H \ No newline at end of file +#endif // SESAMI_UTIL_H \ No newline at end of file diff --git a/arduino_lib/web_services/switchbot_util.h b/arduino_lib/web_services/switchbot_util.h index 5cc41e5f..abddc3cb 100644 --- a/arduino_lib/web_services/switchbot_util.h +++ b/arduino_lib/web_services/switchbot_util.h @@ -1,147 +1,132 @@ #ifndef SWITCHBOT_UTIL_H #define SWITCHBOT_UTIL_H -#include #include - -#include - +#include #include +#include #include // Copied from https://qiita.com/poruruba/items/2ba3f1ff3e3045ce26c1 -void hmac_sha256(const char *p_key, const char *p_payload, unsigned char *p_hmacResult) -{ - mbedtls_md_context_t ctx; - mbedtls_md_type_t md_type = MBEDTLS_MD_SHA256; - mbedtls_md_init(&ctx); - mbedtls_md_setup(&ctx, mbedtls_md_info_from_type(md_type), 1); - mbedtls_md_hmac_starts(&ctx, (const unsigned char *)p_key, strlen(p_key)); - mbedtls_md_hmac_update(&ctx, (const unsigned char *)p_payload, strlen(p_payload)); - mbedtls_md_hmac_finish(&ctx, p_hmacResult); // 32 bytes - mbedtls_md_free(&ctx); +void hmac_sha256(const char *p_key, const char *p_payload, + unsigned char *p_hmacResult) { + mbedtls_md_context_t ctx; + mbedtls_md_type_t md_type = MBEDTLS_MD_SHA256; + mbedtls_md_init(&ctx); + mbedtls_md_setup(&ctx, mbedtls_md_info_from_type(md_type), 1); + mbedtls_md_hmac_starts(&ctx, (const unsigned char *)p_key, strlen(p_key)); + mbedtls_md_hmac_update(&ctx, (const unsigned char *)p_payload, + strlen(p_payload)); + mbedtls_md_hmac_finish(&ctx, p_hmacResult); // 32 bytes + mbedtls_md_free(&ctx); } -std::tuple make_switchbot_sign(String &token, String &secret) -{ - String nonce = ""; - uint32_t t = (uint32_t)std::time(nullptr); - String t_str = String(t) + "000"; - String sign_str = token + t_str + nonce; - unsigned char hmacResult[32]; - hmac_sha256(secret.c_str(), sign_str.c_str(), hmacResult); - String sign = base64::encode(hmacResult, 32); - return std::make_tuple(sign, t_str, nonce); +std::tuple make_switchbot_sign(String &token, + String &secret) { + String nonce = ""; + uint32_t t = (uint32_t)std::time(nullptr); + String t_str = String(t) + "000"; + String sign_str = token + t_str + nonce; + unsigned char hmacResult[32]; + hmac_sha256(secret.c_str(), sign_str.c_str(), hmacResult); + String sign = base64::encode(hmacResult, 32); + return std::make_tuple(sign, t_str, nonce); } -std::optional get_device_list(String &token, String &secret) -{ - HTTPClient http; - String url = "https://api.switch-bot.com/v1.1/devices"; - String sign, t, nonce; - std::tie(sign, t, nonce) = make_switchbot_sign(token, secret); - if (!http.begin(url)) - { - USBSerial.println("http.begin() failed"); - return std::nullopt; - } - http.addHeader("Content-Type", "application/json"); - http.addHeader("Authorization", token); - http.addHeader("sign", sign); - http.addHeader("t", t); - http.addHeader("nonce", nonce); - int responseCode = http.GET(); - String result_body = http.getString(); - http.end(); +std::optional get_device_list(String &token, String &secret) { + HTTPClient http; + String url = "https://api.switch-bot.com/v1.1/devices"; + String sign, t, nonce; + std::tie(sign, t, nonce) = make_switchbot_sign(token, secret); + if (!http.begin(url)) { + USBSerial.println("http.begin() failed"); + return std::nullopt; + } + http.addHeader("Content-Type", "application/json"); + http.addHeader("Authorization", token); + http.addHeader("sign", sign); + http.addHeader("t", t); + http.addHeader("nonce", nonce); + int responseCode = http.GET(); + String result_body = http.getString(); + http.end(); - USBSerial.printf("** GET result **\n"); - USBSerial.printf("responseCode: %d\n", responseCode); - USBSerial.println("body: " + result_body); + USBSerial.printf("** GET result **\n"); + USBSerial.printf("responseCode: %d\n", responseCode); + USBSerial.println("body: " + result_body); - if (responseCode != 200) - { - return std::nullopt; - } - else - { - return result_body; - } + if (responseCode != 200) { + return std::nullopt; + } else { + return result_body; + } } -std::optional get_device_status(String &token, String &secret, String &device_id) -{ - HTTPClient http; - String url = "https://api.switch-bot.com/v1.1/devices/" + device_id + "/status"; - String sign, t, nonce; - std::tie(sign, t, nonce) = make_switchbot_sign(token, secret); - if (!http.begin(url)) - { - USBSerial.println("http.begin() failed"); - return std::nullopt; - } - http.addHeader("Content-Type", "application/json"); - http.addHeader("Authorization", token); - http.addHeader("sign", sign); - http.addHeader("t", t); - http.addHeader("nonce", nonce); - int responseCode = http.GET(); - String result_body = http.getString(); - http.end(); +std::optional get_device_status(String &token, String &secret, + String &device_id) { + HTTPClient http; + String url = + "https://api.switch-bot.com/v1.1/devices/" + device_id + "/status"; + String sign, t, nonce; + std::tie(sign, t, nonce) = make_switchbot_sign(token, secret); + if (!http.begin(url)) { + USBSerial.println("http.begin() failed"); + return std::nullopt; + } + http.addHeader("Content-Type", "application/json"); + http.addHeader("Authorization", token); + http.addHeader("sign", sign); + http.addHeader("t", t); + http.addHeader("nonce", nonce); + int responseCode = http.GET(); + String result_body = http.getString(); + http.end(); - USBSerial.printf("** GET result **\n"); - USBSerial.printf("responseCode: %d\n", responseCode); - USBSerial.println("body: " + result_body); - if (responseCode != 200) - { - return std::nullopt; - } - else - { - return result_body; - } + USBSerial.printf("** GET result **\n"); + USBSerial.printf("responseCode: %d\n", responseCode); + USBSerial.println("body: " + result_body); + if (responseCode != 200) { + return std::nullopt; + } else { + return result_body; + } } -std::optional send_device_command( - String &token, - String &secret, - String &device_id, - String &command_type, - String &command) -{ - HTTPClient http; - String url = "https://api.switch-bot.com/v1.1/devices/" + device_id + "/commands"; - String sign, t, nonce; - std::tie(sign, t, nonce) = make_switchbot_sign(token, secret); - if (!http.begin(url)) - { - USBSerial.println("http.begin() failed"); - return std::nullopt; - } - http.addHeader("Authorization", token); - http.addHeader("sign", sign); - http.addHeader("t", t); - http.addHeader("nonce", nonce); - String body = "{"; - body = body + "\"command\":\"" + command + "\","; - body = body + "\"commandType\":\"" + command_type + "\","; - body = body + "\"parameter\":\"" + "default" + "\""; - body = body + "}"; - int responseCode = http.POST(body); - String result_body = http.getString(); - http.end(); +std::optional send_device_command(String &token, String &secret, + String &device_id, + String &command_type, + String &command) { + HTTPClient http; + String url = + "https://api.switch-bot.com/v1.1/devices/" + device_id + "/commands"; + String sign, t, nonce; + std::tie(sign, t, nonce) = make_switchbot_sign(token, secret); + if (!http.begin(url)) { + USBSerial.println("http.begin() failed"); + return std::nullopt; + } + http.addHeader("Authorization", token); + http.addHeader("sign", sign); + http.addHeader("t", t); + http.addHeader("nonce", nonce); + String body = "{"; + body = body + "\"command\":\"" + command + "\","; + body = body + "\"commandType\":\"" + command_type + "\","; + body = body + "\"parameter\":\"" + "default" + "\""; + body = body + "}"; + int responseCode = http.POST(body); + String result_body = http.getString(); + http.end(); - USBSerial.printf("** POST result **\n"); - USBSerial.printf("responseCode: %d\n", responseCode); - USBSerial.println("body: " + result_body); - if (responseCode != 200) - { - return std::nullopt; - } - else - { - return result_body; - } + USBSerial.printf("** POST result **\n"); + USBSerial.printf("responseCode: %d\n", responseCode); + USBSerial.println("body: " + result_body); + if (responseCode != 200) { + return std::nullopt; + } else { + return result_body; + } } -#endif // SWITCHBOT_UTIL_H \ No newline at end of file +#endif // SWITCHBOT_UTIL_H \ No newline at end of file