diff --git a/.travis.yml b/.travis.yml index ef24321b..f204491a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,38 +1,43 @@ -language: c -dist: trusty -env: - - BD=arduino:avr:uno - - BD=arduino:avr:mega:cpu=atmega2560 - - BD=esp8266:esp8266:nodemcuv2:CpuFrequency=80,FlashSize=4M3M - - BD=esp8266:esp8266:d1_mini:CpuFrequency=80,FlashSize=4M3M - - BD=esp32:esp32:esp32:PartitionScheme=min_spiffs,FlashFreq=80 -before_install: - - "/sbin/start-stop-daemon --start --quiet --pidfile /tmp/custom_xvfb_1.pid --make-pidfile --background --exec /usr/bin/Xvfb -- :1 -ac -screen 0 1280x1024x16" - - sleep 3 - - export DISPLAY=:1.0 - - wget http://downloads.arduino.cc/arduino-$IDE_VERSION-linux64.tar.xz - - tar xf arduino-$IDE_VERSION-linux64.tar.xz - - sudo mv arduino-$IDE_VERSION /usr/local/share/arduino - - sudo ln -s /usr/local/share/arduino/arduino /usr/local/bin/arduino +# Continuous Integration (CI) is the practice, in software +# engineering, of merging all developer working copies with a shared mainline +# several times a day < https://docs.platformio.org/page/ci/index.html > +# +# Documentation: +# +# * Travis CI Embedded Builds with PlatformIO +# < https://docs.travis-ci.com/user/integration/platformio/ > +# +# * PlatformIO integration with Travis CI +# < https://docs.platformio.org/page/ci/travis.html > +# +# * User Guide for `platformio ci` command +# < https://docs.platformio.org/page/userguide/cmd_ci.html > +# +# +# Please choose one of the following templates (proposed below) and uncomment +# it (remove "# " before each line) or use own configuration according to the +# Travis CI documentation (see above). +# + + +# +# Template #1: General project. Test it using existing `platformio.ini`. +# + +language: python +python: + - "2.7" + +sudo: false +cache: + directories: + - "~/.platformio" + install: - - ln -s $PWD /usr/local/share/arduino/OpenMQTTGateway - - rm /usr/local/share/arduino/OpenMQTTGateway/User_config.h - - cp /usr/local/share/arduino/OpenMQTTGateway/tests/Test_config.h /usr/local/share/arduino/OpenMQTTGateway/User_config.h - - rm -rf /usr/local/share/arduino/libraries/RobotIRremote - - cp -R /usr/local/share/arduino/OpenMQTTGateway/lib/. /usr/local/share/arduino/libraries - - cd /usr/local/share/arduino/OpenMQTTGateway - - arduino --pref "boardsmanager.additional.urls=http://arduino.esp8266.com/stable/package_esp8266com_index.json,https://dl.espressif.com/dl/package_esp32_index.json" --save-prefs - - if [[ "$BD" =~ "esp8266:esp8266:" ]]; then - arduino --install-boards esp8266:esp8266:2.4.2; - fi - - if [[ "$BD" =~ "esp32:esp32:" ]]; then - arduino --install-boards esp32:esp32; - rm -rf /home/travis/.arduino15/packages/esp32/hardware/esp32/1.0.2/libraries/BLE; - fi + - pip install -U platformio + - platformio update + - rm /home/travis/build/1technophile/OpenMQTTGateway/main//User_config.h + - cp /home/travis/build/1technophile/OpenMQTTGateway/test/Test_config.h /home/travis/build/1technophile/OpenMQTTGateway/main//User_config.h + script: - - arduino --verify --board $BD $PWD/OpenMQTTGateway.ino -notifications: - email: - on_success: change - on_failure: change - \ No newline at end of file + - platformio run diff --git a/ZgatewayRF315.ino b/ZgatewayRF315.ino deleted file mode 100644 index 329836b1..00000000 --- a/ZgatewayRF315.ino +++ /dev/null @@ -1,155 +0,0 @@ -/* - OpenMQTTGateway - ESP8266 or Arduino program for home automation - - Act as a wifi or ethernet gateway between your 433mhz/infrared IR signal and a MQTT broker - Send and receiving command by MQTT - - This gateway enables to: - - receive MQTT data from a topic and send RF 315Mhz signal corresponding to the received MQTT data - - publish MQTT data to a different topic related to received 315Mhz signal - - Copyright: (c)Florian ROBERT - - This file is part of OpenMQTTGateway. - - OpenMQTTGateway is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - OpenMQTTGateway is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . -*/ -#ifdef ZgatewayRF315 - -#include // library for controling Radio frequency switch - -RCSwitch mySwitch315 = RCSwitch(); - -void setupRF315(){ - - //RF init parameters - mySwitch315.enableTransmit(RF315_EMITTER_PIN); - trc(F("RF315_EMITTER_PIN ")); - trc(RF315_EMITTER_PIN); - mySwitch315.setRepeatTransmit(RF315_EMITTER_REPEAT); - mySwitch315.enableReceive(RF315_RECEIVER_PIN); - trc(F("RF315_RECEIVER_PIN ")); - trc(RF315_RECEIVER_PIN); - trc(F("ZgatewayRF315 setup done ")); -} - -boolean RF315toMQTT(){ - if (mySwitch315.available()){ - trc(F("Creating RF315 buffer")); - const int JSON_MSG_CALC_BUFFER = JSON_OBJECT_SIZE(4); - StaticJsonBuffer jsonBuffer; - JsonObject& RF315data = jsonBuffer.createObject(); - trc(F("Rcv. RF315")); - #ifdef ESP32 - String taskMessage = "RF Task running on core "; - taskMessage = taskMessage + xPortGetCoreID(); - trc(taskMessage); - #endif - RF315data.set("value", (unsigned long)mySwitch315.getReceivedValue()); - RF315data.set("protocol",(int)mySwitch315.getReceivedProtocol()); - RF315data.set("length", (int)mySwitch315.getReceivedBitlength()); - RF315data.set("delay", (int)mySwitch315.getReceivedDelay()); - mySwitch315.resetAvailable(); - - unsigned long MQTTvalue = RF315data.get("value"); - if (!isAduplicate(MQTTvalue) && MQTTvalue!=0) {// conditions to avoid duplications of RF -->MQTT - trc(F("Adv data RF315toMQTT")); - pub(subjectRF315toMQTT,RF315data); - trc(F("Store to avoid duplicate")); - storeValue(MQTTvalue); - if (repeatRF315wMQTT){ - trc(F("Publish RF315 for repeat")); - pub(subjectMQTTtoRF315,RF315data); - } - } - } -} - -#ifdef simpleReceiving - void MQTTtoRF315(char * topicOri, char * datacallback) { - - unsigned long data = strtoul(datacallback, NULL, 10); // we will not be able to pass values > 4294967295 - - // RF315 DATA ANALYSIS - //We look into the subject to see if a special RF protocol is defined - String topic = topicOri; - int valuePRT = 0; - int valuePLSL = 0; - int valueBITS = 0; - int pos = topic.lastIndexOf(RF315protocolKey); - if (pos != -1){ - pos = pos + +strlen(RF315protocolKey); - valuePRT = (topic.substring(pos,pos + 1)).toInt(); - trc(F("RF315 Protocol:")); - trc(valuePRT); - } - //We look into the subject to see if a special RF pulselength is defined - int pos2 = topic.lastIndexOf(RF315pulselengthKey); - if (pos2 != -1) { - pos2 = pos2 + strlen(RF315pulselengthKey); - valuePLSL = (topic.substring(pos2,pos2 + 3)).toInt(); - trc(F("RF315 Pulse Lgth:")); - trc(valuePLSL); - } - int pos3 = topic.lastIndexOf(RF315bitsKey); - if (pos3 != -1){ - pos3 = pos3 + strlen(RF315bitsKey); - valueBITS = (topic.substring(pos3,pos3 + 2)).toInt(); - trc(F("Bits nb:")); - trc(valueBITS); - } - - if ((topic == subjectMQTTtoRF315) && (valuePRT == 0) && (valuePLSL == 0) && (valueBITS == 0)){ - trc(F("MQTTtoRF315 dflt")); - mySwitch315.setProtocol(1,350); - mySwitch315.send(data, 24); - // Acknowledgement to the GTWRF topic - pub(subjectGTWRF315toMQTT, datacallback); - } else if ((valuePRT != 0) || (valuePLSL != 0)|| (valueBITS != 0)){ - trc(F("MQTTtoRF315 usr par.")); - if (valuePRT == 0) valuePRT = 1; - if (valuePLSL == 0) valuePLSL = 350; - if (valueBITS == 0) valueBITS = 24; - trc(valuePRT); - trc(valuePLSL); - trc(valueBITS); - mySwitch315.setProtocol(valuePRT,valuePLSL); - mySwitch315.send(data, valueBITS); - // Acknowledgement to the GTWRF topic - pub(subjectGTWRF315toMQTT, datacallback);// we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also - } - } -#endif - -#ifdef jsonReceiving - void MQTTtoRF315(char * topicOri, JsonObject& RF315data) { // json object decoding - - if (strcmp(topicOri,subjectMQTTtoRF315) == 0){ - trc(F("MQTTtoRF315 json")); - unsigned long data = RF315data["value"]; - if (data != 0) { - int valuePRT = RF315data["protocol"]|1; - int valuePLSL = RF315data["delay"]|350; - int valueBITS = RF315data["length"]|24; - mySwitch315.setProtocol(valuePRT,valuePLSL); - mySwitch315.send(data, valueBITS); - trc(F("MQTTtoRF315 OK")); - pub(subjectGTWRF315toMQTT, RF315data);// we acknowledge the sending by publishing the value to an acknowledgement topic, for the moment even if it is a signal repetition we acknowledge also - }else{ - trc(F("MQTTtoRF315 Fail json")); - } - } - } -#endif -#endif diff --git a/config_RF315.h b/config_RF315.h deleted file mode 100644 index 316a9868..00000000 --- a/config_RF315.h +++ /dev/null @@ -1,62 +0,0 @@ -/* - OpenMQTTGateway - ESP8266 or Arduino program for home automation - - Act as a wifi or ethernet gateway between your 433mhz/infrared IR signal and a MQTT broker - Send and receiving command by MQTT - - This files enables to set your parameter for the radiofrequency gateways (ZgatewayRF315 ) with RCswitch library - - Copyright: (c)Florian ROBERT - - This file is part of OpenMQTTGateway. - - OpenMQTTGateway is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - OpenMQTTGateway is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . -*/ - -/*-------------------RF topics & parameters----------------------*/ -//433Mhz MQTT Subjects and keys -#define subjectMQTTtoRF315 Base_Topic Gateway_Name "/commands/MQTTto315" -#define subjectRF315toMQTT Base_Topic Gateway_Name "/315toMQTT" -#define subjectGTWRF315toMQTT Base_Topic Gateway_Name "/315toMQTT" -#define RF315protocolKey "315_" // protocol will be defined if a subject contains RFprotocolKey followed by a value of 1 digit -#define RF315bitsKey "RFBITS_" // bits will be defined if a subject contains RFbitsKey followed by a value of 2 digits -#define repeatRF315wMQTT false // do we repeat a received signal by using mqtt -/* -RF supported protocols -315_1 -315_2 -315_3 -315_4 -315_5 -315_6 -*/ -#define RF315pulselengthKey "PLSL_" // pulselength will be defined if a subject contains RFprotocolKey followed by a value of 3 digits -// subject monitored to listen traffic processed by other gateways to store data and avoid ntuple -#define subjectMultiGTWRF315 "+/+/315toMQTT" -//RF number of signal repetition -#define RF315_EMITTER_REPEAT 20 - -/*-------------------PIN DEFINITIONS----------------------*/ -#ifdef ESP8266 - #define RF315_RECEIVER_PIN 4 // D3 on nodemcu - #define RF315_EMITTER_PIN 5 // RX on nodemcu -#elif defined(ESP32) - #define RF315_RECEIVER_PIN 13 // D13 on DOIT ESP32 - #define RF315_EMITTER_PIN 12 // D12 on DOIT ESP32 -#else - //IMPORTANT NOTE: On arduino UNO connect IR emitter pin to D9 , comment #define IR_USE_TIMER2 and uncomment #define IR_USE_TIMER1 on library IRremote/IRremoteInt.h so as to free pin D3 for RF RECEIVER PIN - //RF PIN definition - #define RF315_RECEIVER_PIN 1 //1 = D3 on arduino - #define RF315_EMITTER_PIN 4 //4 = D4 on arduino -#endif diff --git a/lib/A6lib/.editorconfig b/lib/A6lib/.editorconfig deleted file mode 100644 index 384f9b23..00000000 --- a/lib/A6lib/.editorconfig +++ /dev/null @@ -1,21 +0,0 @@ -# EditorConfig file: http://EditorConfig.org - -# top-most EditorConfig file -root = true - -# Unix-style newlines with a newline ending every file -[*] -end_of_line = lf -insert_final_newline = false - -# 4 space indentation -[*.{cpp,h}] -indent_style = space -indent_size = 4 -trim_trailing_whitespace = true - -# 2 space indentation -[*.json] -indent_style = space -indent_size = 2 -trim_trailing_whitespace = true diff --git a/lib/A6lib/A6lib.cpp b/lib/A6lib/A6lib.cpp deleted file mode 100644 index a1ecfa54..00000000 --- a/lib/A6lib/A6lib.cpp +++ /dev/null @@ -1,504 +0,0 @@ -#include -#include -#include "A6lib.h" - - -///////////////////////////////////////////// -// Public methods. -// - -A6lib::A6lib(int transmitPin, int receivePin) { -#ifdef ESP8266 - A6conn = new SoftwareSerial(receivePin, transmitPin, false, 1024); -#else - A6conn = new SoftwareSerial(receivePin, transmitPin, false); -#endif -A6conn->setTimeout(100); -} - - -A6lib::~A6lib() { - delete A6conn; -} - - -// Block until the module is ready. -byte A6lib::blockUntilReady(long baudRate) { - - byte response = A6_NOTOK; - while (A6_OK != response) { - response = begin(baudRate); - // This means the modem has failed to initialize and we need to reboot - // it. - if (A6_FAILURE == response) { - return A6_FAILURE; - } - delay(1000); - logln("Waiting for module to be ready..."); - } - return A6_OK; -} - - -// Initialize the software serial connection and change the baud rate from the -// default (autodetected) to the desired speed. -byte A6lib::begin(long baudRate) { - - A6conn->flush(); - - if (A6_OK != setRate(baudRate)) { - return A6_NOTOK; - } - - // Factory reset. - A6command("AT&F", "OK", "yy", A6_CMD_TIMEOUT, 2, NULL); - - // Echo off. - A6command("ATE0", "OK", "yy", A6_CMD_TIMEOUT, 2, NULL); - - // Switch audio to headset. - enableSpeaker(0); - - // Set caller ID on. - A6command("AT+CLIP=1", "OK", "yy", A6_CMD_TIMEOUT, 2, NULL); - - // Set SMS to text mode. - A6command("AT+CMGF=1", "OK", "yy", A6_CMD_TIMEOUT, 2, NULL); - - // Turn SMS indicators off. - A6command("AT+CNMI=1,0", "OK", "yy", A6_CMD_TIMEOUT, 2, NULL); - - // Set SMS storage to the GSM modem. - if (A6_OK != A6command("AT+CPMS=SM,ME,SM", "OK", "yy", A6_CMD_TIMEOUT, 2, NULL)) - // This may sometimes fail, in which case the modem needs to be - // rebooted. - { - return A6_FAILURE; - } - - // Set SMS character set. - setSMScharset("UCS2"); - - return A6_OK; -} - - -// Reboot the module by setting the specified pin HIGH, then LOW. The pin should -// be connected to a P-MOSFET, not the A6's POWER pin. -void A6lib::powerCycle(int pin) { - logln("Power-cycling module..."); - - powerOff(pin); - delay(2000); - - powerOn(pin); - delay(4000); - - powerOff(pin); - // Give the module some time to settle. - logln("Done, waiting for the module to initialize..."); - delay(20000); - logln("Done."); - - A6conn->flush(); -} - - -// Turn the modem power completely off. -void A6lib::powerOff(int pin) { - pinMode(pin, OUTPUT); - digitalWrite(pin, LOW); -} - - -// Turn the modem power on. -void A6lib::powerOn(int pin) { - pinMode(pin, OUTPUT); - digitalWrite(pin, HIGH); -} - - -// Dial a number. -void A6lib::dial(String number) { - char buffer[50]; - - logln("Dialing number..."); - - sprintf(buffer, "ATD%s;", number.c_str()); - A6command(buffer, "OK", "yy", A6_CMD_TIMEOUT, 2, NULL); -} - - -// Redial the last number. -void A6lib::redial() { - logln("Redialing last number..."); - A6command("AT+DLST", "OK", "CONNECT", A6_CMD_TIMEOUT, 2, NULL); -} - - -// Answer a call. -void A6lib::answer() { - A6command("ATA", "OK", "yy", A6_CMD_TIMEOUT, 2, NULL); -} - - -// Hang up the phone. -void A6lib::hangUp() { - A6command("ATH", "OK", "yy", A6_CMD_TIMEOUT, 2, NULL); -} - - -// Check whether there is an active call. -callInfo A6lib::checkCallStatus() { - char number[50]; - String response = ""; - uint32_t respStart = 0, matched = 0; - callInfo cinfo = (const struct callInfo) { - 0 - }; - - // Issue the command and wait for the response. - A6command("AT+CLCC", "OK", "+CLCC", A6_CMD_TIMEOUT, 2, &response); - - // Parse the response if it contains a valid +CLCC. - respStart = response.indexOf("+CLCC"); - if (respStart >= 0) { - matched = sscanf(response.substring(respStart).c_str(), "+CLCC: %d,%d,%d,%d,%d,\"%s\",%d", &cinfo.index, &cinfo.direction, &cinfo.state, &cinfo.mode, &cinfo.multiparty, number, &cinfo.type); - cinfo.number = String(number); - } - - uint8_t comma_index = cinfo.number.indexOf('"'); - if (comma_index != -1) { - logln("Extra comma found."); - cinfo.number = cinfo.number.substring(0, comma_index); - } - - return cinfo; -} - - -// Get the strength of the GSM signal. -int A6lib::getSignalStrength() { - String response = ""; - uint32_t respStart = 0; - int strength, error = 0; - - // Issue the command and wait for the response. - A6command("AT+CSQ", "OK", "+CSQ", A6_CMD_TIMEOUT, 2, &response); - - respStart = response.indexOf("+CSQ"); - if (respStart < 0) { - return 0; - } - - sscanf(response.substring(respStart).c_str(), "+CSQ: %d,%d", - &strength, &error); - - // Bring value range 0..31 to 0..100%, don't mind rounding.. - strength = (strength * 100) / 31; - return strength; -} - - -// Get the real time from the modem. Time will be returned as yy/MM/dd,hh:mm:ss+XX -String A6lib::getRealTimeClock() { - String response = ""; - - // Issue the command and wait for the response. - A6command("AT+CCLK?", "OK", "yy", A6_CMD_TIMEOUT, 1, &response); - int respStart = response.indexOf("+CCLK: \"") + 8; - response.setCharAt(respStart - 1, '-'); - - return response.substring(respStart, response.indexOf("\"")); -} - - -// Send an SMS. -byte A6lib::sendSMS(String number, String text) { - char ctrlZ[2] = { 0x1a, 0x00 }; - char buffer[100]; - - if (text.length() > 159) { - // We can't send messages longer than 160 characters. - return A6_NOTOK; - } - - log("Sending SMS to "); - log(number); - logln("..."); - - sprintf(buffer, "AT+CMGS=\"%s\"", number.c_str()); - A6command(buffer, ">", "yy", A6_CMD_TIMEOUT, 2, NULL); - delay(100); - A6conn->println(text.c_str()); - A6conn->println(ctrlZ); - A6conn->println(); - - return A6_OK; -} - - -// Retrieve the number and locations of unread SMS messages. -int A6lib::getUnreadSMSLocs(int* buf, int maxItems) { - return getSMSLocsOfType(buf, maxItems, "REC UNREAD"); -} - -// Retrieve the number and locations of all SMS messages. -int A6lib::getSMSLocs(int* buf, int maxItems) { - return getSMSLocsOfType(buf, maxItems, "ALL"); -} - -// Retrieve the number and locations of all SMS messages. -int A6lib::getSMSLocsOfType(int* buf, int maxItems, String type) { - String seqStart = "+CMGL: "; - String response = ""; - - String command = "AT+CMGL=\""; - command += type; - command += "\""; - - // Issue the command and wait for the response. - byte status = A6command(command.c_str(), "\xff\r\nOK\r\n", "\r\nOK\r\n", A6_CMD_TIMEOUT, 2, &response); - - int seqStartLen = seqStart.length(); - int responseLen = response.length(); - int index, occurrences = 0; - - // Start looking for the +CMGL string. - for (int i = 0; i < (responseLen - seqStartLen); i++) { - // If we found a response and it's less than occurrences, add it. - if (response.substring(i, i + seqStartLen) == seqStart && occurrences < maxItems) { - // Parse the position out of the reply. - sscanf(response.substring(i, i + 12).c_str(), "+CMGL: %u,%*s", &index); - - buf[occurrences] = index; - occurrences++; - } - } - return occurrences; -} - -// Return the SMS at index. -SMSmessage A6lib::readSMS(int index) { - String response = ""; - char buffer[30]; - - // Issue the command and wait for the response. - sprintf(buffer, "AT+CMGR=%d", index); - A6command(buffer, "\xff\r\nOK\r\n", "\r\nOK\r\n", A6_CMD_TIMEOUT, 2, &response); - - char message[200]; - char number[50]; - char date[50]; - char type[10]; - int respStart = 0, matched = 0; - SMSmessage sms = (const struct SMSmessage) { - "", "", "" - }; - - // Parse the response if it contains a valid +CLCC. - respStart = response.indexOf("+CMGR"); - if (respStart >= 0) { - // Parse the message header. - matched = sscanf(response.substring(respStart).c_str(), "+CMGR: \"REC %s\",\"%s\",,\"%s\"\r\n", type, number, date); - sms.number = String(number); - sms.date = String(date); - // The rest is the message, extract it. - sms.message = response.substring(strlen(type) + strlen(number) + strlen(date) + 24, response.length() - 8); - } - return sms; -} - -// Delete the SMS at index. -byte A6lib::deleteSMS(int index) { - char buffer[20]; - sprintf(buffer, "AT+CMGD=%d", index); - return A6command(buffer, "OK", "yy", A6_CMD_TIMEOUT, 2, NULL); -} - -// Delete SMS with special flags -byte A6lib::deleteSMS(int index, int flag) { - char buffer[20]; - String command = "AT+CMGD="; - command += String(index); - command += ","; - command += String(flag); - return A6command(command.c_str(), "OK", "yy", A6_CMD_TIMEOUT, 2, NULL); -} // AT+CMGD=1,4 delete all SMS from the storage area - - -// Set the SMS charset. -byte A6lib::setSMScharset(String charset) { - char buffer[30]; - - sprintf(buffer, "AT+CSCS=\"%s\"", charset.c_str()); - return A6command(buffer, "OK", "yy", A6_CMD_TIMEOUT, 2, NULL); -} - - -// Set the volume for the speaker. level should be a number between 5 and -// 8 inclusive. -void A6lib::setVol(byte level) { - char buffer[30]; - - // level should be between 5 and 8. - level = _min(_max(level, 5), 8); - sprintf(buffer, "AT+CLVL=%d", level); - A6command(buffer, "OK", "yy", A6_CMD_TIMEOUT, 2, NULL); -} - - -// Enable the speaker, rather than the headphones. Pass 0 to route audio through -// headphones, 1 through speaker. -void A6lib::enableSpeaker(byte enable) { - char buffer[30]; - - // enable should be between 0 and 1. - enable = _min(_max(enable, 0), 1); - sprintf(buffer, "AT+SNFS=%d", enable); - A6command(buffer, "OK", "yy", A6_CMD_TIMEOUT, 2, NULL); -} - - - -///////////////////////////////////////////// -// Private methods. -// - - -// Autodetect the connection rate. - -long A6lib::detectRate() { - unsigned long rate = 0; - unsigned long rates[] = {9600, 115200}; - - // Try to autodetect the rate. - logln("Autodetecting connection rate..."); - for (int i = 0; i < countof(rates); i++) { - rate = rates[i]; - A6conn->begin(rate); - log("Trying rate "); - log(rate); - logln("..."); - - delay(100); - if (A6command("\rAT", "OK", "+CME", 2000, 2, NULL) == A6_OK) { - return rate; - } - } - - logln("Couldn't detect the rate."); - - return A6_NOTOK; -} - - -// Set the A6 baud rate. -char A6lib::setRate(long baudRate) { - int rate = 0; - - rate = detectRate(); - if (rate == A6_NOTOK) { - return A6_NOTOK; - } - - // The rate is already the desired rate, return. - //if (rate == baudRate) return OK; - - logln("Setting baud rate on the module..."); - - // Change the rate to the requested. - char buffer[30]; - sprintf(buffer, "AT+IPR=%d", baudRate); - A6command(buffer, "OK", "+IPR=", A6_CMD_TIMEOUT, 3, NULL); - - logln("Switching to the new rate..."); - // Begin the connection again at the requested rate. - A6conn->begin(baudRate); - logln("Rate set."); - - return A6_OK; -} - - -// Read some data from the A6 in a non-blocking manner. -String A6lib::read() { - String reply = ""; - if (A6conn->available()) { - reply = A6conn->readString(); - } - - // XXX: Replace NULs with \xff so we can match on them. - for (int x = 0; x < reply.length(); x++) { - if (reply.charAt(x) == 0) { - reply.setCharAt(x, 255); - } - } - return reply; -} - - -// Issue a command. -byte A6lib::A6command(const char *command, const char *resp1, const char *resp2, int timeout, int repetitions, String *response) { - byte returnValue = A6_NOTOK; - byte count = 0; - - // Get rid of any buffered output. - A6conn->flush(); - - while (count < repetitions && returnValue != A6_OK) { - log("Issuing command: "); - logln(command); - - A6conn->write(command); - A6conn->write('\r'); - - if (A6waitFor(resp1, resp2, timeout, response) == A6_OK) { - returnValue = A6_OK; - } else { - returnValue = A6_NOTOK; - } - count++; - } - return returnValue; -} - - -// Wait for responses. -byte A6lib::A6waitFor(const char *resp1, const char *resp2, int timeout, String *response) { - unsigned long entry = millis(); - int count = 0; - String reply = ""; - byte retVal = 99; - do { - reply += read(); - #ifdef ESP8266 - yield(); - #endif - } while (((reply.indexOf(resp1) + reply.indexOf(resp2)) == -2) && ((millis() - entry) < timeout)); - - if (reply != "") { - log("Reply in "); - log((millis() - entry)); - log(" ms: "); - logln(reply); - } - - if (response != NULL) { - *response = reply; - } - - if ((millis() - entry) >= timeout) { - retVal = A6_TIMEOUT; - logln("Timed out."); - } else { - if (reply.indexOf(resp1) + reply.indexOf(resp2) > -2) { - logln("Reply OK."); - retVal = A6_OK; - } else { - logln("Reply NOT OK."); - retVal = A6_NOTOK; - } - } - return retVal; -} diff --git a/lib/A6lib/A6lib.h b/lib/A6lib/A6lib.h deleted file mode 100644 index b4a6cfe3..00000000 --- a/lib/A6lib/A6lib.h +++ /dev/null @@ -1,111 +0,0 @@ -#ifndef A6lib_h -#define A6lib_h - -#include -#include "SoftwareSerial.h" - -#ifdef DEBUG -#define log(msg) Serial.print(msg) -#define logln(msg) Serial.println(msg) -#else -#define log(msg) -#define logln(msg) -#endif - -#define countof(a) (sizeof(a) / sizeof(a[0])) - -#define A6_OK 0 -#define A6_NOTOK 1 -#define A6_TIMEOUT 2 -#define A6_FAILURE 3 - -#define A6_CMD_TIMEOUT 5000 - - -enum call_direction { - DIR_OUTGOING = 0, - DIR_INCOMING = 1 -}; - -enum call_state { - CALL_ACTIVE = 0, - CALL_HELD = 1, - CALL_DIALING = 2, - CALL_ALERTING = 3, - CALL_INCOMING = 4, - CALL_WAITING = 5, - CALL_RELEASE = 7 -}; - -enum call_mode { - MODE_VOICE = 0, - MODE_DATA = 1, - MODE_FAX = 2, - MODE_VOICE_THEN_DATA_VMODE = 3, - MODE_VOICE_AND_DATA_VMODE = 4, - MODE_VOICE_AND_FAX_VMODE = 5, - MODE_VOICE_THEN_DATA_DMODE = 6, - MODE_VOICE_AND_DATA_DMODE = 7, - MODE_VOICE_AND_FAX_FMODE = 8, - MODE_UNKNOWN = 9 -}; - -struct SMSmessage { - String number; - String date; - String message; -}; - -struct callInfo { - int index; - call_direction direction; - call_state state; - call_mode mode; - int multiparty; - String number; - int type; -}; - - -class A6lib { -public: - A6lib(int transmitPin, int receivePin); - ~A6lib(); - - byte begin(long baudRate); - byte blockUntilReady(long baudRate); - - void powerCycle(int pin); - void powerOn(int pin); - void powerOff(int pin); - - void dial(String number); - void redial(); - void answer(); - void hangUp(); - callInfo checkCallStatus(); - int getSignalStrength(); - - byte sendSMS(String number, String text); - int getUnreadSMSLocs(int* buf, int maxItems); - int getSMSLocs(int* buf, int maxItems); - int getSMSLocsOfType(int* buf, int maxItems, String type); - SMSmessage readSMS(int index); - byte deleteSMS(int index); - byte deleteSMS(int index, int flag); - byte setSMScharset(String charset); - - void setVol(byte level); - void enableSpeaker(byte enable); - - String getRealTimeClock(); - - SoftwareSerial *A6conn; -private: - String read(); - byte A6command(const char *command, const char *resp1, const char *resp2, int timeout, int repetitions, String *response); - byte A6waitFor(const char *resp1, const char *resp2, int timeout, String *response); - long detectRate(); - char setRate(long baudRate); -}; -#endif diff --git a/lib/A6lib/LICENSE.md b/lib/A6lib/LICENSE.md deleted file mode 100644 index 87c01331..00000000 --- a/lib/A6lib/LICENSE.md +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2016 Stavros Korokithakis - -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. diff --git a/lib/A6lib/README.md b/lib/A6lib/README.md deleted file mode 100644 index 83a00fc4..00000000 --- a/lib/A6lib/README.md +++ /dev/null @@ -1,65 +0,0 @@ -# A6lib - -An ESP8266/Arduino library for communicating with the AI-Thinker A6 GSM module. -It will probably also work with other GSM modules that use the AT command set, -like the SIM900. - -## Details - -This library is an adaptation of -[this sample module](https://github.com/SensorsIot/A6-GSM-Module). It is still -very incomplete, but at least it works somewhat. Please feel free to issue pull -requests to improve it. - -## Usage - -If you have the A6 breakout board, connect the Tx and Rx pins to your ESP8266. -The example assumes the TX pin is connected to D5 and the RX to D6. A6lib can -power-cycle the module if you connect a MOSFET to a pin and control the A6's -power supply with it. - -For a sample circuit that uses this library, have a look at [the A6/ESP8266 -breakout board](https://gitlab.com/stavros/A6-ESP8266-breakout/) I designed. - -The A6's PWR pin should be permanently connected to Vcc (if you think that's -wrong or know a better way, please open an issue). - -The code looks something like this: - -~~~ -// Instantiate the class with Tx, Rx (remember to swap them when connecting to -the A6, i.e. connect the A6's Rx pin to D6). -A6lib A6c(D6, D5); - -// Initialize the modem, rebooting it if it fails to become ready. -do { - // Power-cycle the module to reset it. - A6c.powerCycle(D0); -} while (A6c.blockUntilReady(9600) != A6_OK); - -// Start and place a call. -A6c.dial("1234567890"); -delay(8000); - -A6c.hangUp(); -delay(8000); - -A6c.redial(); -delay(8000); - -// Send a message. -A6c.sendSMS("+1234567890", "Hello there!"); - -// Get an SMS message from memory. -SMSmessage sms = A6c.readSMS(3); - -// Delete an SMS message. -A6c.deleteSMS(3); - -callInfo cinfo = A6c.checkCallStatus(); -// This will be the calling number, "1234567890". -cinfo.number; -~~~ - -This library doesn't currently include any code to connect to the internet, but -a PR adding that would be very welcome. diff --git a/lib/A6lib/examples/dial/dial.ino b/lib/A6lib/examples/dial/dial.ino deleted file mode 100644 index 0a96541b..00000000 --- a/lib/A6lib/examples/dial/dial.ino +++ /dev/null @@ -1,44 +0,0 @@ -#include - -#ifndef ESP8266 -#define D0 0 -#define D5 8 -#define D6 7 -#endif - -// Instantiate the library with TxPin, RxPin. -A6lib A6l(D6, D5); - -void setup() { - Serial.begin(115200); - - delay(1000); - - // Power-cycle the module to reset it. - A6l.powerCycle(D0); - A6l.blockUntilReady(9600); -} - -void loop() { - Serial.println("Checking call status..."); - callInfo cinfo = A6l.checkCallStatus(); - Serial.println("Call status checked."); - - int sigStrength = A6l.getSignalStrength(); - Serial.print("Signal strength percentage: "); - Serial.println(sigStrength); - - delay(5000); - - if (cinfo.number != NULL) { - if (cinfo.direction == DIR_INCOMING && cinfo.number == "919999999999") { - A6l.answer(); - } else { - A6l.hangUp(); - } - delay(1000); - } else { - Serial.println("No number yet."); - delay(1000); - } -} diff --git a/lib/A6lib/examples/serial_relay/serial_relay.ino b/lib/A6lib/examples/serial_relay/serial_relay.ino deleted file mode 100644 index 535aa34f..00000000 --- a/lib/A6lib/examples/serial_relay/serial_relay.ino +++ /dev/null @@ -1,30 +0,0 @@ -#include - -#ifndef ESP8266 -#define D0 0 -#define D5 8 -#define D6 7 -#endif - -// Instantiate the library with TxPin, RxPin. -A6lib A6l(D6, D5); - -void setup() { - Serial.begin(115200); - - delay(1000); - - // Power-cycle the module to reset it. - A6l.powerCycle(D0); - A6l.blockUntilReady(9600); -} - -void loop() { - // Relay things between Serial and the module's SoftSerial. - while (A6l.A6conn->available() > 0) { - Serial.write(A6l.A6conn->read()); - } - while (Serial.available() > 0) { - A6l.A6conn->write(Serial.read()); - } -} diff --git a/lib/A6lib/examples/sms/sms.ino b/lib/A6lib/examples/sms/sms.ino deleted file mode 100644 index cd483de3..00000000 --- a/lib/A6lib/examples/sms/sms.ino +++ /dev/null @@ -1,51 +0,0 @@ -#include - -#ifdef ESP8266 -#define D0 0 -#define D5 8 -#define D6 7 -#endif - -// Instantiate the library with TxPin, RxPin. -A6lib A6l(D6, D5); - -int unreadSMSLocs[30] = {0}; -int unreadSMSNum = 0; -SMSmessage sms; - -void setup() { - Serial.begin(115200); - - delay(1000); - - // Power-cycle the module to reset it. - A6l.powerCycle(D0); - A6l.blockUntilReady(9600); -} - -void loop() { - String myNumber = "+1132352890"; - - callInfo cinfo = A6l.checkCallStatus(); - if (cinfo.direction == DIR_INCOMING) { - if (myNumber.endsWith(cinfo.number)) { - // If the number that sent the SMS is ours, reply. - A6l.sendSMS(myNumber, "I can't come to the phone right now, I'm a machine."); - A6l.hangUp(); - } - - // Get the memory locations of unread SMS messages. - unreadSMSNum = A6l.getUnreadSMSLocs(unreadSMSLocs, 30); - - for (int i = 0; i < unreadSMSNum; i++) { - Serial.print("New message at index: "); - Serial.println(unreadSMSLocs[i], DEC); - - sms = A6l.readSMS(unreadSMSLocs[i]); - Serial.println(sms.number); - Serial.println(sms.date); - Serial.println(sms.message); - } - delay(1000); - } -} diff --git a/lib/A6lib/keywords.txt b/lib/A6lib/keywords.txt deleted file mode 100644 index 1076a88d..00000000 --- a/lib/A6lib/keywords.txt +++ /dev/null @@ -1,35 +0,0 @@ -####################################### -# A6 GSM communication module -# (esp8266) -####################################### - -####################################### -# Datatypes (KEYWORD1) -####################################### - -A6lib KEYWORD1 -callInfo KEYWORD1 - -####################################### -# Methods and Functions (KEYWORD2) -####################################### - -begin KEYWORD2 -powerCycle KEYWORD2 - -dial KEYWORD2 -redial KEYWORD2 -hangUp KEYWORD2 -checkCallStatus KEYWORD2 -getSignalStrength KEYWORD2 - -sendSMS KEYWORD2 - -setVol KEYWORD2 -enableSpeaker KEYWORD2 - -A6conn KEYWORD2 - -####################################### -# Constants (LITERAL1) -####################################### diff --git a/lib/A6lib/library.json b/lib/A6lib/library.json deleted file mode 100644 index 9023366f..00000000 --- a/lib/A6lib/library.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "A6lib", - "keywords": [ - "A6", "GSM", "mobile" - ], - "description": "An ESP8266/Arduino library for communicating with the A6 GSM module.", - "repository": - { - "type": "git", - "url": "https://github.com/skorokithakis/A6lib" - }, - "frameworks": "arduino", - "platforms": "*" -} diff --git a/lib/A6lib/library.properties b/lib/A6lib/library.properties deleted file mode 100644 index e7b65988..00000000 --- a/lib/A6lib/library.properties +++ /dev/null @@ -1,9 +0,0 @@ -name=A6lib -version=0.1.3 -author=Stavros Korokithakis -maintainer=Stavros Korokithakis (hi@stavros.io) -sentence=An ESP8266/Arduino library for communicating with the A6 GSM module. -paragraph= -category=Communication -url=https://github.com/skorokithakis/A6lib -architectures=* diff --git a/lib/A6lib/sscanf.cpp b/lib/A6lib/sscanf.cpp deleted file mode 100644 index bafaeeab..00000000 --- a/lib/A6lib/sscanf.cpp +++ /dev/null @@ -1,262 +0,0 @@ -/* - * Copyright (c) 2000-2002 Opsycon AB (www.opsycon.se) - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * This product includes software developed by Opsycon AB. - * 4. The name of the author may not be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS - * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - * - */ - -#include -#include -#include -#include -#include - -#define MAXLN 200 -#define ISSPACE " \t\n\r\f\v\"" - -size_t strcspn(const char *p, const char *s) { - int i, j; - - for (i = 0; p[i]; i++) { - for (j = 0; s[j]; j++) { - if (s[j] == p[i]) { - break; - } - } - if (s[j]) { - break; - } - } - return (i); -} - -char * _getbase(char *p, int *basep) { - if (p[0] == '0') { - switch (p[1]) { - case 'x': - *basep = 16; - break; - case 't': - case 'n': - *basep = 10; - break; - case 'o': - *basep = 8; - break; - default: - *basep = 10; - return (p); - } - return (p + 2); - } - *basep = 10; - return (p); -} - -/* - * _atob(vp,p,base) - */ -int _atob(uint32_t *vp, char *p, int base) { - uint32_t value, v1, v2; - char *q, tmp[20]; - int digit; - - if (p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) { - base = 16; - p += 2; - } - - if (base == 16 && (q = strchr(p, '.')) != 0) { - if (q - p > sizeof(tmp) - 1) { - return (0); - } - - strncpy(tmp, p, q - p); - tmp[q - p] = '\0'; - if (!_atob(&v1, tmp, 16)) { - return (0); - } - - q++; - if (strchr(q, '.')) { - return (0); - } - - if (!_atob(&v2, q, 16)) { - return (0); - } - *vp = (v1 << 16) + v2; - return (1); - } - - value = *vp = 0; - for (; *p; p++) { - if (*p >= '0' && *p <= '9') { - digit = *p - '0'; - } else if (*p >= 'a' && *p <= 'f') { - digit = *p - 'a' + 10; - } else if (*p >= 'A' && *p <= 'F') { - digit = *p - 'A' + 10; - } else { - return (0); - } - - if (digit >= base) { - return (0); - } - value *= base; - value += digit; - } - *vp = value; - return (1); -} - -/* - * atob(vp,p,base) - * converts p to binary result in vp, rtn 1 on success - */ -int atob(uint32_t *vp, char *p, int base) { - uint32_t v; - if (base == 0) { - p = _getbase(p, &base); - } - if (_atob(&v, p, base)) { - *vp = v; - return (1); - } - return (0); -} - -/* - * vsscanf(buf,fmt,ap) - */ - -int vsscanf(const char *buf, const char *s, va_list ap) { - uint32_t count, noassign, width, base, lflag; - const char *tc; - char *t, tmp[MAXLN]; - - count = noassign = width = lflag = 0; - while (*s && *buf) { - while (isspace(*s)) { - s++; - } - if (*s == '%') { - s++; - for (; *s; s++) { - if (strchr("dibouxcsefg%", *s)) { - break; - } - if (*s == '*') { - noassign = 1; - } else if (*s == 'l' || *s == 'L') { - lflag = 1; - } else if (*s >= '1' && *s <= '9') { - for (tc = s; isdigit(*s); s++); - strncpy(tmp, tc, s - tc); - tmp[s - tc] = '\0'; - atob(&width, tmp, 10); - s--; - } - } - if (*s == 's') { - while (isspace(*buf)) { - buf++; - } - if (!width) { - width = strcspn(buf, ISSPACE); - } - if (!noassign) { - strncpy(t = va_arg(ap, char *), buf, width); - t[width] = '\0'; - } - buf += width; - } else if (*s == 'c') { - if (!width) { - width = 1; - } - if (!noassign) { - strncpy(t = va_arg(ap, char *), buf, width); - t[width] = '\0'; - } - buf += width; - } else if (strchr("dobxu", *s)) { - while (isspace(*buf)) { - buf++; - } - if (*s == 'd' || *s == 'u') { - base = 10; - } else if (*s == 'x') { - base = 16; - } else if (*s == 'o') { - base = 8; - } else if (*s == 'b') { - base = 2; - } - if (!width) { - if (isspace(*(s + 1)) || *(s + 1) == 0) { - width = strcspn(buf, ISSPACE); - } else { - width = strchr(buf, *(s + 1)) - buf; - } - } - strncpy(tmp, buf, width); - tmp[width] = '\0'; - buf += width; - if (!noassign) { - atob(va_arg(ap, uint32_t *), tmp, base); - } - } - if (!noassign) { - count++; - } - width = noassign = lflag = 0; - s++; - } else { - while (isspace(*buf)) { - buf++; - } - if (*s != *buf) { - break; - } else { - s++, buf++; - } - } - } - return (count); -} - - -int __attribute__((used)) sscanf(const char *buf, const char *fmt, ...) { - int count; - va_list ap; - - va_start(ap, fmt); - count = vsscanf(buf, fmt, ap); - va_end(ap); - return (count); -} diff --git a/lib/Adafruit_Sensor/Adafruit_Sensor.h b/lib/Adafruit_Sensor/Adafruit_Sensor.h deleted file mode 100644 index 7742afc1..00000000 --- a/lib/Adafruit_Sensor/Adafruit_Sensor.h +++ /dev/null @@ -1,154 +0,0 @@ -/* -* Copyright (C) 2008 The Android Open Source Project -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software< /span> -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ - -/* Update by K. Townsend (Adafruit Industries) for lighter typedefs, and - * extended sensor support to include color, voltage and current */ - -#ifndef _ADAFRUIT_SENSOR_H -#define _ADAFRUIT_SENSOR_H - -#if ARDUINO >= 100 - #include "Arduino.h" - #include "Print.h" -#else - #include "WProgram.h" -#endif - -/* Intentionally modeled after sensors.h in the Android API: - * https://github.com/android/platform_hardware_libhardware/blob/master/include/hardware/sensors.h */ - -/* Constants */ -#define SENSORS_GRAVITY_EARTH (9.80665F) /**< Earth's gravity in m/s^2 */ -#define SENSORS_GRAVITY_MOON (1.6F) /**< The moon's gravity in m/s^2 */ -#define SENSORS_GRAVITY_SUN (275.0F) /**< The sun's gravity in m/s^2 */ -#define SENSORS_GRAVITY_STANDARD (SENSORS_GRAVITY_EARTH) -#define SENSORS_MAGFIELD_EARTH_MAX (60.0F) /**< Maximum magnetic field on Earth's surface */ -#define SENSORS_MAGFIELD_EARTH_MIN (30.0F) /**< Minimum magnetic field on Earth's surface */ -#define SENSORS_PRESSURE_SEALEVELHPA (1013.25F) /**< Average sea level pressure is 1013.25 hPa */ -#define SENSORS_DPS_TO_RADS (0.017453293F) /**< Degrees/s to rad/s multiplier */ -#define SENSORS_GAUSS_TO_MICROTESLA (100) /**< Gauss to micro-Tesla multiplier */ - -/** Sensor types */ -typedef enum -{ - SENSOR_TYPE_ACCELEROMETER = (1), /**< Gravity + linear acceleration */ - SENSOR_TYPE_MAGNETIC_FIELD = (2), - SENSOR_TYPE_ORIENTATION = (3), - SENSOR_TYPE_GYROSCOPE = (4), - SENSOR_TYPE_LIGHT = (5), - SENSOR_TYPE_PRESSURE = (6), - SENSOR_TYPE_PROXIMITY = (8), - SENSOR_TYPE_GRAVITY = (9), - SENSOR_TYPE_LINEAR_ACCELERATION = (10), /**< Acceleration not including gravity */ - SENSOR_TYPE_ROTATION_VECTOR = (11), - SENSOR_TYPE_RELATIVE_HUMIDITY = (12), - SENSOR_TYPE_AMBIENT_TEMPERATURE = (13), - SENSOR_TYPE_VOLTAGE = (15), - SENSOR_TYPE_CURRENT = (16), - SENSOR_TYPE_COLOR = (17) -} sensors_type_t; - -/** struct sensors_vec_s is used to return a vector in a common format. */ -typedef struct { - union { - float v[3]; - struct { - float x; - float y; - float z; - }; - /* Orientation sensors */ - struct { - float roll; /**< Rotation around the longitudinal axis (the plane body, 'X axis'). Roll is positive and increasing when moving downward. -90°<=roll<=90° */ - float pitch; /**< Rotation around the lateral axis (the wing span, 'Y axis'). Pitch is positive and increasing when moving upwards. -180°<=pitch<=180°) */ - float heading; /**< Angle between the longitudinal axis (the plane body) and magnetic north, measured clockwise when viewing from the top of the device. 0-359° */ - }; - }; - int8_t status; - uint8_t reserved[3]; -} sensors_vec_t; - -/** struct sensors_color_s is used to return color data in a common format. */ -typedef struct { - union { - float c[3]; - /* RGB color space */ - struct { - float r; /**< Red component */ - float g; /**< Green component */ - float b; /**< Blue component */ - }; - }; - uint32_t rgba; /**< 24-bit RGBA value */ -} sensors_color_t; - -/* Sensor event (36 bytes) */ -/** struct sensor_event_s is used to provide a single sensor event in a common format. */ -typedef struct -{ - int32_t version; /**< must be sizeof(struct sensors_event_t) */ - int32_t sensor_id; /**< unique sensor identifier */ - int32_t type; /**< sensor type */ - int32_t reserved0; /**< reserved */ - int32_t timestamp; /**< time is in milliseconds */ - union - { - float data[4]; - sensors_vec_t acceleration; /**< acceleration values are in meter per second per second (m/s^2) */ - sensors_vec_t magnetic; /**< magnetic vector values are in micro-Tesla (uT) */ - sensors_vec_t orientation; /**< orientation values are in degrees */ - sensors_vec_t gyro; /**< gyroscope values are in rad/s */ - float temperature; /**< temperature is in degrees centigrade (Celsius) */ - float distance; /**< distance in centimeters */ - float light; /**< light in SI lux units */ - float pressure; /**< pressure in hectopascal (hPa) */ - float relative_humidity; /**< relative humidity in percent */ - float current; /**< current in milliamps (mA) */ - float voltage; /**< voltage in volts (V) */ - sensors_color_t color; /**< color in RGB component values */ - }; -} sensors_event_t; - -/* Sensor details (40 bytes) */ -/** struct sensor_s is used to describe basic information about a specific sensor. */ -typedef struct -{ - char name[12]; /**< sensor name */ - int32_t version; /**< version of the hardware + driver */ - int32_t sensor_id; /**< unique sensor identifier */ - int32_t type; /**< this sensor's type (ex. SENSOR_TYPE_LIGHT) */ - float max_value; /**< maximum value of this sensor's value in SI units */ - float min_value; /**< minimum value of this sensor's value in SI units */ - float resolution; /**< smallest difference between two values reported by this sensor */ - int32_t min_delay; /**< min delay in microseconds between events. zero = not a constant rate */ -} sensor_t; - -class Adafruit_Sensor { - public: - // Constructor(s) - Adafruit_Sensor() {} - virtual ~Adafruit_Sensor() {} - - // These must be defined by the subclass - virtual void enableAutoRange(bool enabled) {}; - virtual bool getEvent(sensors_event_t*) = 0; - virtual void getSensor(sensor_t*) = 0; - - private: - bool _autoRange; -}; - -#endif diff --git a/lib/Adafruit_Sensor/README.md b/lib/Adafruit_Sensor/README.md deleted file mode 100644 index a4cd6aeb..00000000 --- a/lib/Adafruit_Sensor/README.md +++ /dev/null @@ -1,221 +0,0 @@ -# Adafruit Unified Sensor Driver # - -Many small embedded systems exist to collect data from sensors, analyse the data, and either take an appropriate action or send that sensor data to another system for processing. - -One of the many challenges of embedded systems design is the fact that parts you used today may be out of production tomorrow, or system requirements may change and you may need to choose a different sensor down the road. - -Creating new drivers is a relatively easy task, but integrating them into existing systems is both error prone and time consuming since sensors rarely use the exact same units of measurement. - -By reducing all data to a single **sensors\_event\_t** 'type' and settling on specific, **standardised SI units** for each sensor family the same sensor types return values that are comparable with any other similar sensor. This enables you to switch sensor models with very little impact on the rest of the system, which can help mitigate some of the risks and problems of sensor availability and code reuse. - -The unified sensor abstraction layer is also useful for data-logging and data-transmission since you only have one well-known type to log or transmit over the air or wire. - -## Unified Sensor Drivers ## - -The following drivers are based on the Adafruit Unified Sensor Driver: - -**Accelerometers** - - [Adafruit\_ADXL345](https://github.com/adafruit/Adafruit_ADXL345) - - [Adafruit\_LSM303DLHC](https://github.com/adafruit/Adafruit_LSM303DLHC) - - [Adafruit\_MMA8451\_Library](https://github.com/adafruit/Adafruit_MMA8451_Library) - -**Gyroscope** - - [Adafruit\_L3GD20\_U](https://github.com/adafruit/Adafruit_L3GD20_U) - -**Light** - - [Adafruit\_TSL2561](https://github.com/adafruit/Adafruit_TSL2561) - - [Adafruit\_TSL2591\_Library](https://github.com/adafruit/Adafruit_TSL2591_Library) - -**Magnetometers** - - [Adafruit\_LSM303DLHC](https://github.com/adafruit/Adafruit_LSM303DLHC) - - [Adafruit\_HMC5883\_Unified](https://github.com/adafruit/Adafruit_HMC5883_Unified) - -**Barometric Pressure** - - [Adafruit\_BMP085\_Unified](https://github.com/adafruit/Adafruit_BMP085_Unified) - - [Adafruit\_BMP183\_Unified\_Library](https://github.com/adafruit/Adafruit_BMP183_Unified_Library) - -**Humidity & Temperature** - - [DHT-sensor-library](https://github.com/adafruit/DHT-sensor-library) - -**Orientation** - - [Adafruit_BNO055](https://github.com/adafruit/Adafruit_BNO055) - -## How Does it Work? ## - -Any driver that supports the Adafruit unified sensor abstraction layer will implement the Adafruit\_Sensor base class. There are two main typedefs and one enum defined in Adafruit_Sensor.h that are used to 'abstract' away the sensor details and values: - -**Sensor Types (sensors\_type\_t)** - -These pre-defined sensor types are used to properly handle the two related typedefs below, and allows us determine what types of units the sensor uses, etc. - -``` -/** Sensor types */ -typedef enum -{ - SENSOR_TYPE_ACCELEROMETER = (1), - SENSOR_TYPE_MAGNETIC_FIELD = (2), - SENSOR_TYPE_ORIENTATION = (3), - SENSOR_TYPE_GYROSCOPE = (4), - SENSOR_TYPE_LIGHT = (5), - SENSOR_TYPE_PRESSURE = (6), - SENSOR_TYPE_PROXIMITY = (8), - SENSOR_TYPE_GRAVITY = (9), - SENSOR_TYPE_LINEAR_ACCELERATION = (10), - SENSOR_TYPE_ROTATION_VECTOR = (11), - SENSOR_TYPE_RELATIVE_HUMIDITY = (12), - SENSOR_TYPE_AMBIENT_TEMPERATURE = (13), - SENSOR_TYPE_VOLTAGE = (15), - SENSOR_TYPE_CURRENT = (16), - SENSOR_TYPE_COLOR = (17) -} sensors_type_t; -``` - -**Sensor Details (sensor\_t)** - -This typedef describes the specific capabilities of this sensor, and allows us to know what sensor we are using beneath the abstraction layer. - -``` -/* Sensor details (40 bytes) */ -/** struct sensor_s is used to describe basic information about a specific sensor. */ -typedef struct -{ - char name[12]; - int32_t version; - int32_t sensor_id; - int32_t type; - float max_value; - float min_value; - float resolution; - int32_t min_delay; -} sensor_t; -``` - -The individual fields are intended to be used as follows: - -- **name**: The sensor name or ID, up to a maximum of twelve characters (ex. "MPL115A2") -- **version**: The version of the sensor HW and the driver to allow us to differentiate versions of the board or driver -- **sensor\_id**: A unique sensor identifier that is used to differentiate this specific sensor instance from any others that are present on the system or in the sensor network -- **type**: The sensor type, based on **sensors\_type\_t** in sensors.h -- **max\_value**: The maximum value that this sensor can return (in the appropriate SI unit) -- **min\_value**: The minimum value that this sensor can return (in the appropriate SI unit) -- **resolution**: The smallest difference between two values that this sensor can report (in the appropriate SI unit) -- **min\_delay**: The minimum delay in microseconds between two sensor events, or '0' if there is no constant sensor rate - -**Sensor Data/Events (sensors\_event\_t)** - -This typedef is used to return sensor data from any sensor supported by the abstraction layer, using standard SI units and scales. - -``` -/* Sensor event (36 bytes) */ -/** struct sensor_event_s is used to provide a single sensor event in a common format. */ -typedef struct -{ - int32_t version; - int32_t sensor_id; - int32_t type; - int32_t reserved0; - int32_t timestamp; - union - { - float data[4]; - sensors_vec_t acceleration; - sensors_vec_t magnetic; - sensors_vec_t orientation; - sensors_vec_t gyro; - float temperature; - float distance; - float light; - float pressure; - float relative_humidity; - float current; - float voltage; - sensors_color_t color; - }; -} sensors_event_t; -``` -It includes the following fields: - -- **version**: Contain 'sizeof(sensors\_event\_t)' to identify which version of the API we're using in case this changes in the future -- **sensor\_id**: A unique sensor identifier that is used to differentiate this specific sensor instance from any others that are present on the system or in the sensor network (must match the sensor\_id value in the corresponding sensor\_t enum above!) -- **type**: the sensor type, based on **sensors\_type\_t** in sensors.h -- **timestamp**: time in milliseconds when the sensor value was read -- **data[4]**: An array of four 32-bit values that allows us to encapsulate any type of sensor data via a simple union (further described below) - -**Required Functions** - -In addition to the two standard types and the sensor type enum, all drivers based on Adafruit_Sensor must also implement the following two functions: - -``` -bool getEvent(sensors_event_t*); -``` -Calling this function will populate the supplied sensors\_event\_t reference with the latest available sensor data. You should call this function as often as you want to update your data. - -``` -void getSensor(sensor_t*); -``` -Calling this function will provide some basic information about the sensor (the sensor name, driver version, min and max values, etc. - -**Standardised SI values for sensors\_event\_t** - -A key part of the abstraction layer is the standardisation of values on SI units of a particular scale, which is accomplished via the data[4] union in sensors\_event\_t above. This 16 byte union includes fields for each main sensor type, and uses the following SI units and scales: - -- **acceleration**: values are in **meter per second per second** (m/s^2) -- **magnetic**: values are in **micro-Tesla** (uT) -- **orientation**: values are in **degrees** -- **gyro**: values are in **rad/s** -- **temperature**: values in **degrees centigrade** (Celsius) -- **distance**: values are in **centimeters** -- **light**: values are in **SI lux** units -- **pressure**: values are in **hectopascal** (hPa) -- **relative\_humidity**: values are in **percent** -- **current**: values are in **milliamps** (mA) -- **voltage**: values are in **volts** (V) -- **color**: values are in 0..1.0 RGB channel luminosity and 32-bit RGBA format - -## The Unified Driver Abstraction Layer in Practice ## - -Using the unified sensor abstraction layer is relatively easy once a compliant driver has been created. - -Every compliant sensor can now be read using a single, well-known 'type' (sensors\_event\_t), and there is a standardised way of interrogating a sensor about its specific capabilities (via sensor\_t). - -An example of reading the [TSL2561](https://github.com/adafruit/Adafruit_TSL2561) light sensor can be seen below: - -``` - Adafruit_TSL2561 tsl = Adafruit_TSL2561(TSL2561_ADDR_FLOAT, 12345); - ... - /* Get a new sensor event */ - sensors_event_t event; - tsl.getEvent(&event); - - /* Display the results (light is measured in lux) */ - if (event.light) - { - Serial.print(event.light); Serial.println(" lux"); - } - else - { - /* If event.light = 0 lux the sensor is probably saturated - and no reliable data could be generated! */ - Serial.println("Sensor overload"); - } -``` - -Similarly, we can get the basic technical capabilities of this sensor with the following code: - -``` - sensor_t sensor; - - sensor_t sensor; - tsl.getSensor(&sensor); - - /* Display the sensor details */ - Serial.println("------------------------------------"); - Serial.print ("Sensor: "); Serial.println(sensor.name); - Serial.print ("Driver Ver: "); Serial.println(sensor.version); - Serial.print ("Unique ID: "); Serial.println(sensor.sensor_id); - Serial.print ("Max Value: "); Serial.print(sensor.max_value); Serial.println(" lux"); - Serial.print ("Min Value: "); Serial.print(sensor.min_value); Serial.println(" lux"); - Serial.print ("Resolution: "); Serial.print(sensor.resolution); Serial.println(" lux"); - Serial.println("------------------------------------"); - Serial.println(""); -``` diff --git a/lib/Adafruit_Sensor/library.properties b/lib/Adafruit_Sensor/library.properties deleted file mode 100644 index fa7eefa7..00000000 --- a/lib/Adafruit_Sensor/library.properties +++ /dev/null @@ -1,9 +0,0 @@ -name=Adafruit Unified Sensor -version=1.0.2 -author=Adafruit -maintainer=Adafruit -sentence=Required for all Adafruit Unified Sensor based libraries. -paragraph=A unified sensor abstraction layer used by many Adafruit sensor libraries. -category=Sensors -url=https://github.com/adafruit/Adafruit_Sensor -architectures=* diff --git a/lib/Adafruit_TSL2561/.github/ISSUE_TEMPLATE.md b/lib/Adafruit_TSL2561/.github/ISSUE_TEMPLATE.md deleted file mode 100644 index f0e26146..00000000 --- a/lib/Adafruit_TSL2561/.github/ISSUE_TEMPLATE.md +++ /dev/null @@ -1,46 +0,0 @@ -Thank you for opening an issue on an Adafruit Arduino library repository. To -improve the speed of resolution please review the following guidelines and -common troubleshooting steps below before creating the issue: - -- **Do not use GitHub issues for troubleshooting projects and issues.** Instead use - the forums at http://forums.adafruit.com to ask questions and troubleshoot why - something isn't working as expected. In many cases the problem is a common issue - that you will more quickly receive help from the forum community. GitHub issues - are meant for known defects in the code. If you don't know if there is a defect - in the code then start with troubleshooting on the forum first. - -- **If following a tutorial or guide be sure you didn't miss a step.** Carefully - check all of the steps and commands to run have been followed. Consult the - forum if you're unsure or have questions about steps in a guide/tutorial. - -- **For Arduino projects check these very common issues to ensure they don't apply**: - - - For uploading sketches or communicating with the board make sure you're using - a **USB data cable** and **not** a **USB charge-only cable**. It is sometimes - very hard to tell the difference between a data and charge cable! Try using the - cable with other devices or swapping to another cable to confirm it is not - the problem. - - - **Be sure you are supplying adequate power to the board.** Check the specs of - your board and plug in an external power supply. In many cases just - plugging a board into your computer is not enough to power it and other - peripherals. - - - **Double check all soldering joints and connections.** Flakey connections - cause many mysterious problems. See the [guide to excellent soldering](https://learn.adafruit.com/adafruit-guide-excellent-soldering/tools) for examples of good solder joints. - - - **Ensure you are using an official Arduino or Adafruit board.** We can't - guarantee a clone board will have the same functionality and work as expected - with this code and don't support them. - -If you're sure this issue is a defect in the code and checked the steps above -please fill in the following fields to provide enough troubleshooting information. -You may delete the guideline and text above to just leave the following details: - -- Arduino board: **INSERT ARDUINO BOARD NAME/TYPE HERE** - -- Arduino IDE version (found in Arduino -> About Arduino menu): **INSERT ARDUINO - VERSION HERE** - -- List the steps to reproduce the problem below (if possible attach a sketch or - copy the sketch code in too): **LIST REPRO STEPS BELOW** diff --git a/lib/Adafruit_TSL2561/.github/PULL_REQUEST_TEMPLATE.md b/lib/Adafruit_TSL2561/.github/PULL_REQUEST_TEMPLATE.md deleted file mode 100644 index 7b641eb8..00000000 --- a/lib/Adafruit_TSL2561/.github/PULL_REQUEST_TEMPLATE.md +++ /dev/null @@ -1,26 +0,0 @@ -Thank you for creating a pull request to contribute to Adafruit's GitHub code! -Before you open the request please review the following guidelines and tips to -help it be more easily integrated: - -- **Describe the scope of your change--i.e. what the change does and what parts - of the code were modified.** This will help us understand any risks of integrating - the code. - -- **Describe any known limitations with your change.** For example if the change - doesn't apply to a supported platform of the library please mention it. - -- **Please run any tests or examples that can exercise your modified code.** We - strive to not break users of the code and running tests/examples helps with this - process. - -Thank you again for contributing! We will try to test and integrate the change -as soon as we can, but be aware we have many GitHub repositories to manage and -can't immediately respond to every request. There is no need to bump or check in -on a pull request (it will clutter the discussion of the request). - -Also don't be worried if the request is closed or not integrated--sometimes the -priorities of Adafruit's GitHub code (education, ease of use) might not match the -priorities of the pull request. Don't fret, the open source community thrives on -forks and GitHub makes it easy to keep your changes in a forked repo. - -After reviewing the guidelines above you can delete this text from the pull request. diff --git a/lib/Adafruit_TSL2561/.travis.yml b/lib/Adafruit_TSL2561/.travis.yml deleted file mode 100644 index a22fcb56..00000000 --- a/lib/Adafruit_TSL2561/.travis.yml +++ /dev/null @@ -1,27 +0,0 @@ -language: c -sudo: false - -# Blacklist -branches: - except: - - gh-pages - -env: - global: - - PRETTYNAME="Adafruit TSL2561 Arduino Library" -# Optional, will default to "$TRAVIS_BUILD_DIR/Doxyfile" -# - DOXYFILE: $TRAVIS_BUILD_DIR/Doxyfile - -before_install: - - source <(curl -SLs https://raw.githubusercontent.com/adafruit/travis-ci-arduino/master/install.sh) - -install: - - arduino --install-library "Adafruit Unified Sensor" - -script: - - build_main_platforms - -# Generate and deploy documentation -after_success: - - source <(curl -SLs https://raw.githubusercontent.com/adafruit/travis-ci-arduino/master/library_check.sh) - - source <(curl -SLs https://raw.githubusercontent.com/adafruit/travis-ci-arduino/master/doxy_gen_and_deploy.sh) \ No newline at end of file diff --git a/lib/Adafruit_TSL2561/Adafruit_TSL2561_U.cpp b/lib/Adafruit_TSL2561/Adafruit_TSL2561_U.cpp deleted file mode 100644 index 69663fa9..00000000 --- a/lib/Adafruit_TSL2561/Adafruit_TSL2561_U.cpp +++ /dev/null @@ -1,575 +0,0 @@ -/*! - * @file Adafruit_TSL2561_U.cpp - * - * @mainpage Adafruit TSL2561 Light/Lux sensor driver - * - * @section intro_sec Introduction - * - * This is the documentation for Adafruit's TSL2561 driver for the - * Arduino platform. It is designed specifically to work with the - * Adafruit TSL2561 breakout: http://www.adafruit.com/products/439 - * - * These sensors use I2C to communicate, 2 pins (SCL+SDA) are required - * to interface with the breakout. - * - * Adafruit invests time and resources providing this open source code, - * please support Adafruit and open-source hardware by purchasing - * products from Adafruit! - * - * @section dependencies Dependencies - * - * This library depends on - * Adafruit_Sensor being present on your system. Please make sure you have - * installed the latest version before using this library. - * - * @section author Author - * - * Written by Kevin "KTOWN" Townsend for Adafruit Industries. - * - * @section license License - * - * BSD license, all text here must be included in any redistribution. - * - * @section HISTORY - * - * v2.0 - Rewrote driver for Adafruit_Sensor and Auto-Gain support, and - * added lux clipping check (returns 0 lux on sensor saturation) - * v1.0 - First release (previously TSL2561) -*/ -/**************************************************************************/ - -#include "Adafruit_TSL2561_U.h" - -/*========================================================================*/ -/* CONSTRUCTORS */ -/*========================================================================*/ - -/**************************************************************************/ -/*! - @brief Constructor - @param addr The I2C address this chip can be found on, 0x29, 0x39 or 0x49 - @param sensorID An optional ID that will be placed in sensor events to help - keep track if you have many sensors in use -*/ -/**************************************************************************/ -Adafruit_TSL2561_Unified::Adafruit_TSL2561_Unified(uint8_t addr, int32_t sensorID) -{ - _addr = addr; - _tsl2561Initialised = false; - _tsl2561AutoGain = false; - _tsl2561IntegrationTime = TSL2561_INTEGRATIONTIME_13MS; - _tsl2561Gain = TSL2561_GAIN_1X; - _tsl2561SensorID = sensorID; -} - -/*========================================================================*/ -/* PUBLIC FUNCTIONS */ -/*========================================================================*/ - -/**************************************************************************/ -/*! - @brief Initializes I2C and configures the sensor with default Wire I2C - (call this function before doing anything else) - @returns True if sensor is found and initialized, false otherwise. -*/ -/**************************************************************************/ -boolean Adafruit_TSL2561_Unified::begin() -{ - _i2c = &Wire; - _i2c->begin(); - return init(); -} - -/**************************************************************************/ -/*! - @brief Initializes I2C and configures the sensor with provided I2C device - (call this function before doing anything else) - @param theWire A pointer to any I2C interface (e.g. &Wire1) - @returns True if sensor is found and initialized, false otherwise. -*/ -/**************************************************************************/ -boolean Adafruit_TSL2561_Unified::begin(TwoWire *theWire) -{ - _i2c = theWire; - _i2c-> begin(); - return init(); -} - -/**************************************************************************/ -/*! - @brief Initializes I2C connection and settings. - Attempts to determine if the sensor is contactable, then sets up a default - integration time and gain. Then powers down the chip. - @returns True if sensor is found and initialized, false otherwise. -*/ -/**************************************************************************/ -boolean Adafruit_TSL2561_Unified::init() -{ - /* Make sure we're actually connected */ - uint8_t x = read8(TSL2561_REGISTER_ID); - if (x & 0xF0 != 0x10) { // ID code for TSL2561 - return false; - } - _tsl2561Initialised = true; - - /* Set default integration time and gain */ - setIntegrationTime(_tsl2561IntegrationTime); - setGain(_tsl2561Gain); - - /* Note: by default, the device is in power down mode on bootup */ - disable(); - - return true; -} - -/**************************************************************************/ -/*! - @brief Enables or disables the auto-gain settings when reading - data from the sensor - @param enable Set to true to enable, False to disable -*/ -/**************************************************************************/ -void Adafruit_TSL2561_Unified::enableAutoRange(bool enable) -{ - _tsl2561AutoGain = enable ? true : false; -} - -/**************************************************************************/ -/*! - @brief Sets the integration time for the TSL2561. Higher time means - more light captured (better for low light conditions) but will - take longer to run readings. - @param time The amount of time we'd like to add up values -*/ -/**************************************************************************/ -void Adafruit_TSL2561_Unified::setIntegrationTime(tsl2561IntegrationTime_t time) -{ - if (!_tsl2561Initialised) begin(); - - /* Enable the device by setting the control bit to 0x03 */ - enable(); - - /* Update the timing register */ - write8(TSL2561_COMMAND_BIT | TSL2561_REGISTER_TIMING, time | _tsl2561Gain); - - /* Update value placeholders */ - _tsl2561IntegrationTime = time; - - /* Turn the device off to save power */ - disable(); -} - -/**************************************************************************/ -/*! - @brief Adjusts the gain on the TSL2561 (adjusts the sensitivity to light) - @param gain The value we'd like to set the gain to -*/ -/**************************************************************************/ -void Adafruit_TSL2561_Unified::setGain(tsl2561Gain_t gain) -{ - if (!_tsl2561Initialised) begin(); - - /* Enable the device by setting the control bit to 0x03 */ - enable(); - - /* Update the timing register */ - write8(TSL2561_COMMAND_BIT | TSL2561_REGISTER_TIMING, _tsl2561IntegrationTime | gain); - - /* Update value placeholders */ - _tsl2561Gain = gain; - - /* Turn the device off to save power */ - disable(); -} - -/**************************************************************************/ -/*! - @brief Gets the broadband (mixed lighting) and IR only values from - the TSL2561, adjusting gain if auto-gain is enabled - @param broadband Pointer to a uint16_t we will fill with a sensor - reading from the IR+visible light diode. - @param ir Pointer to a uint16_t we will fill with a sensor the - IR-only light diode. -*/ -/**************************************************************************/ -void Adafruit_TSL2561_Unified::getLuminosity (uint16_t *broadband, uint16_t *ir) -{ - bool valid = false; - - if (!_tsl2561Initialised) begin(); - - /* If Auto gain disabled get a single reading and continue */ - if(!_tsl2561AutoGain) - { - getData (broadband, ir); - return; - } - - /* Read data until we find a valid range */ - bool _agcCheck = false; - do - { - uint16_t _b, _ir; - uint16_t _hi, _lo; - tsl2561IntegrationTime_t _it = _tsl2561IntegrationTime; - - /* Get the hi/low threshold for the current integration time */ - switch(_it) - { - case TSL2561_INTEGRATIONTIME_13MS: - _hi = TSL2561_AGC_THI_13MS; - _lo = TSL2561_AGC_TLO_13MS; - break; - case TSL2561_INTEGRATIONTIME_101MS: - _hi = TSL2561_AGC_THI_101MS; - _lo = TSL2561_AGC_TLO_101MS; - break; - default: - _hi = TSL2561_AGC_THI_402MS; - _lo = TSL2561_AGC_TLO_402MS; - break; - } - - getData(&_b, &_ir); - - /* Run an auto-gain check if we haven't already done so ... */ - if (!_agcCheck) - { - if ((_b < _lo) && (_tsl2561Gain == TSL2561_GAIN_1X)) - { - /* Increase the gain and try again */ - setGain(TSL2561_GAIN_16X); - /* Drop the previous conversion results */ - getData(&_b, &_ir); - /* Set a flag to indicate we've adjusted the gain */ - _agcCheck = true; - } - else if ((_b > _hi) && (_tsl2561Gain == TSL2561_GAIN_16X)) - { - /* Drop gain to 1x and try again */ - setGain(TSL2561_GAIN_1X); - /* Drop the previous conversion results */ - getData(&_b, &_ir); - /* Set a flag to indicate we've adjusted the gain */ - _agcCheck = true; - } - else - { - /* Nothing to look at here, keep moving .... - Reading is either valid, or we're already at the chips limits */ - *broadband = _b; - *ir = _ir; - valid = true; - } - } - else - { - /* If we've already adjusted the gain once, just return the new results. - This avoids endless loops where a value is at one extreme pre-gain, - and the the other extreme post-gain */ - *broadband = _b; - *ir = _ir; - valid = true; - } - } while (!valid); -} - - - -/**************************************************************************/ -/*! - Enables the device -*/ -/**************************************************************************/ -void Adafruit_TSL2561_Unified::enable(void) -{ - /* Enable the device by setting the control bit to 0x03 */ - write8(TSL2561_COMMAND_BIT | TSL2561_REGISTER_CONTROL, TSL2561_CONTROL_POWERON); -} - -/**************************************************************************/ -/*! - Disables the device (putting it in lower power sleep mode) -*/ -/**************************************************************************/ -void Adafruit_TSL2561_Unified::disable(void) -{ - /* Turn the device off to save power */ - write8(TSL2561_COMMAND_BIT | TSL2561_REGISTER_CONTROL, TSL2561_CONTROL_POWEROFF); -} - -/**************************************************************************/ -/*! - Private function to read luminosity on both channels -*/ -/**************************************************************************/ -void Adafruit_TSL2561_Unified::getData (uint16_t *broadband, uint16_t *ir) -{ - /* Enable the device by setting the control bit to 0x03 */ - enable(); - - /* Wait x ms for ADC to complete */ - switch (_tsl2561IntegrationTime) - { - case TSL2561_INTEGRATIONTIME_13MS: - delay(TSL2561_DELAY_INTTIME_13MS); // KTOWN: Was 14ms - break; - case TSL2561_INTEGRATIONTIME_101MS: - delay(TSL2561_DELAY_INTTIME_101MS); // KTOWN: Was 102ms - break; - default: - delay(TSL2561_DELAY_INTTIME_402MS); // KTOWN: Was 403ms - break; - } - - /* Reads a two byte value from channel 0 (visible + infrared) */ - *broadband = read16(TSL2561_COMMAND_BIT | TSL2561_WORD_BIT | TSL2561_REGISTER_CHAN0_LOW); - - /* Reads a two byte value from channel 1 (infrared) */ - *ir = read16(TSL2561_COMMAND_BIT | TSL2561_WORD_BIT | TSL2561_REGISTER_CHAN1_LOW); - - /* Turn the device off to save power */ - disable(); -} - - -/**************************************************************************/ -/*! - @brief Converts the raw sensor values to the standard SI lux equivalent. - @param broadband The 16-bit sensor reading from the IR+visible light diode. - @param ir The 16-bit sensor reading from the IR-only light diode. - @returns The integer Lux value we calcuated. - Returns 0 if the sensor is saturated and the values are - unreliable, or 65536 if the sensor is saturated. -*/ -/**************************************************************************/ -/**************************************************************************/ -/*! - - Returns -*/ -/**************************************************************************/ -uint32_t Adafruit_TSL2561_Unified::calculateLux(uint16_t broadband, uint16_t ir) -{ - unsigned long chScale; - unsigned long channel1; - unsigned long channel0; - - /* Make sure the sensor isn't saturated! */ - uint16_t clipThreshold; - switch (_tsl2561IntegrationTime) - { - case TSL2561_INTEGRATIONTIME_13MS: - clipThreshold = TSL2561_CLIPPING_13MS; - break; - case TSL2561_INTEGRATIONTIME_101MS: - clipThreshold = TSL2561_CLIPPING_101MS; - break; - default: - clipThreshold = TSL2561_CLIPPING_402MS; - break; - } - - /* Return 65536 lux if the sensor is saturated */ - if ((broadband > clipThreshold) || (ir > clipThreshold)) - { - return 65536; - } - - /* Get the correct scale depending on the intergration time */ - switch (_tsl2561IntegrationTime) - { - case TSL2561_INTEGRATIONTIME_13MS: - chScale = TSL2561_LUX_CHSCALE_TINT0; - break; - case TSL2561_INTEGRATIONTIME_101MS: - chScale = TSL2561_LUX_CHSCALE_TINT1; - break; - default: /* No scaling ... integration time = 402ms */ - chScale = (1 << TSL2561_LUX_CHSCALE); - break; - } - - /* Scale for gain (1x or 16x) */ - if (!_tsl2561Gain) chScale = chScale << 4; - - /* Scale the channel values */ - channel0 = (broadband * chScale) >> TSL2561_LUX_CHSCALE; - channel1 = (ir * chScale) >> TSL2561_LUX_CHSCALE; - - /* Find the ratio of the channel values (Channel1/Channel0) */ - unsigned long ratio1 = 0; - if (channel0 != 0) ratio1 = (channel1 << (TSL2561_LUX_RATIOSCALE+1)) / channel0; - - /* round the ratio value */ - unsigned long ratio = (ratio1 + 1) >> 1; - - unsigned int b, m; - -#ifdef TSL2561_PACKAGE_CS - if ((ratio >= 0) && (ratio <= TSL2561_LUX_K1C)) - {b=TSL2561_LUX_B1C; m=TSL2561_LUX_M1C;} - else if (ratio <= TSL2561_LUX_K2C) - {b=TSL2561_LUX_B2C; m=TSL2561_LUX_M2C;} - else if (ratio <= TSL2561_LUX_K3C) - {b=TSL2561_LUX_B3C; m=TSL2561_LUX_M3C;} - else if (ratio <= TSL2561_LUX_K4C) - {b=TSL2561_LUX_B4C; m=TSL2561_LUX_M4C;} - else if (ratio <= TSL2561_LUX_K5C) - {b=TSL2561_LUX_B5C; m=TSL2561_LUX_M5C;} - else if (ratio <= TSL2561_LUX_K6C) - {b=TSL2561_LUX_B6C; m=TSL2561_LUX_M6C;} - else if (ratio <= TSL2561_LUX_K7C) - {b=TSL2561_LUX_B7C; m=TSL2561_LUX_M7C;} - else if (ratio > TSL2561_LUX_K8C) - {b=TSL2561_LUX_B8C; m=TSL2561_LUX_M8C;} -#else - if ((ratio >= 0) && (ratio <= TSL2561_LUX_K1T)) - {b=TSL2561_LUX_B1T; m=TSL2561_LUX_M1T;} - else if (ratio <= TSL2561_LUX_K2T) - {b=TSL2561_LUX_B2T; m=TSL2561_LUX_M2T;} - else if (ratio <= TSL2561_LUX_K3T) - {b=TSL2561_LUX_B3T; m=TSL2561_LUX_M3T;} - else if (ratio <= TSL2561_LUX_K4T) - {b=TSL2561_LUX_B4T; m=TSL2561_LUX_M4T;} - else if (ratio <= TSL2561_LUX_K5T) - {b=TSL2561_LUX_B5T; m=TSL2561_LUX_M5T;} - else if (ratio <= TSL2561_LUX_K6T) - {b=TSL2561_LUX_B6T; m=TSL2561_LUX_M6T;} - else if (ratio <= TSL2561_LUX_K7T) - {b=TSL2561_LUX_B7T; m=TSL2561_LUX_M7T;} - else if (ratio > TSL2561_LUX_K8T) - {b=TSL2561_LUX_B8T; m=TSL2561_LUX_M8T;} -#endif - - unsigned long temp; - temp = ((channel0 * b) - (channel1 * m)); - - /* Do not allow negative lux value */ - if (temp < 0) temp = 0; - - /* Round lsb (2^(LUX_SCALE-1)) */ - temp += (1 << (TSL2561_LUX_LUXSCALE-1)); - - /* Strip off fractional portion */ - uint32_t lux = temp >> TSL2561_LUX_LUXSCALE; - - /* Signal I2C had no errors */ - return lux; -} - -/**************************************************************************/ -/*! - @brief Gets the most recent sensor event - @param event Pointer to a sensor_event_t type that will be filled - with the lux value, timestamp, data type and sensor ID. - @returns True if sensor reading is between 0 and 65535 lux, - false if sensor is saturated -*/ -/**************************************************************************/ -bool Adafruit_TSL2561_Unified::getEvent(sensors_event_t *event) -{ - uint16_t broadband, ir; - - /* Clear the event */ - memset(event, 0, sizeof(sensors_event_t)); - - event->version = sizeof(sensors_event_t); - event->sensor_id = _tsl2561SensorID; - event->type = SENSOR_TYPE_LIGHT; - event->timestamp = millis(); - - /* Calculate the actual lux value */ - getLuminosity(&broadband, &ir); - event->light = calculateLux(broadband, ir); - - if (event->light == 65536) { - return false; - } - return true; -} - -/**************************************************************************/ -/*! - @brief Gets the sensor_t data - @param sensor A pointer to a sensor_t structure that we will fill with - details about the TSL2561 and its capabilities -*/ -/**************************************************************************/ -void Adafruit_TSL2561_Unified::getSensor(sensor_t *sensor) -{ - /* Clear the sensor_t object */ - memset(sensor, 0, sizeof(sensor_t)); - - /* Insert the sensor name in the fixed length char array */ - strncpy (sensor->name, "TSL2561", sizeof(sensor->name) - 1); - sensor->name[sizeof(sensor->name)- 1] = 0; - sensor->version = 1; - sensor->sensor_id = _tsl2561SensorID; - sensor->type = SENSOR_TYPE_LIGHT; - sensor->min_delay = 0; - sensor->max_value = 17000.0; /* Based on trial and error ... confirm! */ - sensor->min_value = 1.0; - sensor->resolution = 1.0; -} - - - -/*========================================================================*/ -/* PRIVATE FUNCTIONS */ -/*========================================================================*/ - -/**************************************************************************/ -/*! - @brief Writes a register and an 8 bit value over I2C - @param reg I2C register to write the value to - @param value The 8-bit value we're writing to the register -*/ -/**************************************************************************/ -void Adafruit_TSL2561_Unified::write8 (uint8_t reg, uint8_t value) -{ - _i2c->beginTransmission(_addr); - _i2c->write(reg); - _i2c->write(value); - _i2c->endTransmission(); -} - -/**************************************************************************/ -/*! - @brief Reads an 8 bit value over I2C - @param reg I2C register to read from - @returns 8-bit value containing single byte data read -*/ -/**************************************************************************/ -uint8_t Adafruit_TSL2561_Unified::read8(uint8_t reg) -{ - _i2c->beginTransmission(_addr); - _i2c->write(reg); - _i2c->endTransmission(); - - _i2c->requestFrom(_addr, 1); - return _i2c-> read(); -} - -/**************************************************************************/ -/*! - @brief Reads a 16 bit values over I2C - @param reg I2C register to read from - @returns 16-bit value containing 2-byte data read -*/ -/**************************************************************************/ -uint16_t Adafruit_TSL2561_Unified::read16(uint8_t reg) -{ - uint16_t x, t; - - _i2c->beginTransmission(_addr); - _i2c->write(reg); - _i2c->endTransmission(); - - _i2c->requestFrom(_addr, 2); - t = _i2c->read(); - x = _i2c->read(); - x <<= 8; - x |= t; - return x; -} diff --git a/lib/Adafruit_TSL2561/Adafruit_TSL2561_U.h b/lib/Adafruit_TSL2561/Adafruit_TSL2561_U.h deleted file mode 100644 index e1aa191f..00000000 --- a/lib/Adafruit_TSL2561/Adafruit_TSL2561_U.h +++ /dev/null @@ -1,203 +0,0 @@ -/*! - * @file Adafruit_TSL2561_U.h - * - * This is part of Adafruit's FXOS8700 driver for the Arduino platform. It is - * designed specifically to work with the Adafruit FXOS8700 breakout: - * https://www.adafruit.com/products/3463 - * - * These sensors use I2C to communicate, 2 pins (SCL+SDA) are required - * to interface with the breakout. - * - * Adafruit invests time and resources providing this open source code, - * please support Adafruit and open-source hardware by purchasing - * products from Adafruit! - * - * Written by Kevin "KTOWN" Townsend for Adafruit Industries. - * - * BSD license, all text here must be included in any redistribution. - * - */ - -#ifndef ADAFRUIT_TSL2561_H_ -#define ADAFRUIT_TSL2561_H_ - -#include -#include -#include - -#define TSL2561_VISIBLE 2 ///< channel 0 - channel 1 -#define TSL2561_INFRARED 1 ///< channel 1 -#define TSL2561_FULLSPECTRUM 0 ///< channel 0 - -// I2C address options -#define TSL2561_ADDR_LOW (0x29) ///< Default address (pin pulled low) -#define TSL2561_ADDR_FLOAT (0x39) ///< Default address (pin left floating) -#define TSL2561_ADDR_HIGH (0x49) ///< Default address (pin pulled high) - -// Lux calculations differ slightly for CS package -//#define TSL2561_PACKAGE_CS ///< Chip scale package -#define TSL2561_PACKAGE_T_FN_CL ///< Dual Flat No-Lead package - -#define TSL2561_COMMAND_BIT (0x80) ///< Must be 1 -#define TSL2561_CLEAR_BIT (0x40) ///< Clears any pending interrupt (write 1 to clear) -#define TSL2561_WORD_BIT (0x20) ///< 1 = read/write word (rather than byte) -#define TSL2561_BLOCK_BIT (0x10) ///< 1 = using block read/write - -#define TSL2561_CONTROL_POWERON (0x03) ///< Control register setting to turn on -#define TSL2561_CONTROL_POWEROFF (0x00) ///< Control register setting to turn off - -#define TSL2561_LUX_LUXSCALE (14) ///< Scale by 2^14 -#define TSL2561_LUX_RATIOSCALE (9) ///< Scale ratio by 2^9 -#define TSL2561_LUX_CHSCALE (10) ///< Scale channel values by 2^10 -#define TSL2561_LUX_CHSCALE_TINT0 (0x7517) ///< 322/11 * 2^TSL2561_LUX_CHSCALE -#define TSL2561_LUX_CHSCALE_TINT1 (0x0FE7) ///< 322/81 * 2^TSL2561_LUX_CHSCALE - -// T, FN and CL package values -#define TSL2561_LUX_K1T (0x0040) ///< 0.125 * 2^RATIO_SCALE -#define TSL2561_LUX_B1T (0x01f2) ///< 0.0304 * 2^LUX_SCALE -#define TSL2561_LUX_M1T (0x01be) ///< 0.0272 * 2^LUX_SCALE -#define TSL2561_LUX_K2T (0x0080) ///< 0.250 * 2^RATIO_SCALE -#define TSL2561_LUX_B2T (0x0214) ///< 0.0325 * 2^LUX_SCALE -#define TSL2561_LUX_M2T (0x02d1) ///< 0.0440 * 2^LUX_SCALE -#define TSL2561_LUX_K3T (0x00c0) ///< 0.375 * 2^RATIO_SCALE -#define TSL2561_LUX_B3T (0x023f) ///< 0.0351 * 2^LUX_SCALE -#define TSL2561_LUX_M3T (0x037b) ///< 0.0544 * 2^LUX_SCALE -#define TSL2561_LUX_K4T (0x0100) ///< 0.50 * 2^RATIO_SCALE -#define TSL2561_LUX_B4T (0x0270) ///< 0.0381 * 2^LUX_SCALE -#define TSL2561_LUX_M4T (0x03fe) ///< 0.0624 * 2^LUX_SCALE -#define TSL2561_LUX_K5T (0x0138) ///< 0.61 * 2^RATIO_SCALE -#define TSL2561_LUX_B5T (0x016f) ///< 0.0224 * 2^LUX_SCALE -#define TSL2561_LUX_M5T (0x01fc) ///< 0.0310 * 2^LUX_SCALE -#define TSL2561_LUX_K6T (0x019a) ///< 0.80 * 2^RATIO_SCALE -#define TSL2561_LUX_B6T (0x00d2) ///< 0.0128 * 2^LUX_SCALE -#define TSL2561_LUX_M6T (0x00fb) ///< 0.0153 * 2^LUX_SCALE -#define TSL2561_LUX_K7T (0x029a) ///< 1.3 * 2^RATIO_SCALE -#define TSL2561_LUX_B7T (0x0018) ///< 0.00146 * 2^LUX_SCALE -#define TSL2561_LUX_M7T (0x0012) ///< 0.00112 * 2^LUX_SCALE -#define TSL2561_LUX_K8T (0x029a) ///< 1.3 * 2^RATIO_SCALE -#define TSL2561_LUX_B8T (0x0000) ///< 0.000 * 2^LUX_SCALE -#define TSL2561_LUX_M8T (0x0000) ///< 0.000 * 2^LUX_SCALE - -// CS package values -#define TSL2561_LUX_K1C (0x0043) ///< 0.130 * 2^RATIO_SCALE -#define TSL2561_LUX_B1C (0x0204) ///< 0.0315 * 2^LUX_SCALE -#define TSL2561_LUX_M1C (0x01ad) ///< 0.0262 * 2^LUX_SCALE -#define TSL2561_LUX_K2C (0x0085) ///< 0.260 * 2^RATIO_SCALE -#define TSL2561_LUX_B2C (0x0228) ///< 0.0337 * 2^LUX_SCALE -#define TSL2561_LUX_M2C (0x02c1) ///< 0.0430 * 2^LUX_SCALE -#define TSL2561_LUX_K3C (0x00c8) ///< 0.390 * 2^RATIO_SCALE -#define TSL2561_LUX_B3C (0x0253) ///< 0.0363 * 2^LUX_SCALE -#define TSL2561_LUX_M3C (0x0363) ///< 0.0529 * 2^LUX_SCALE -#define TSL2561_LUX_K4C (0x010a) ///< 0.520 * 2^RATIO_SCALE -#define TSL2561_LUX_B4C (0x0282) ///< 0.0392 * 2^LUX_SCALE -#define TSL2561_LUX_M4C (0x03df) ///< 0.0605 * 2^LUX_SCALE -#define TSL2561_LUX_K5C (0x014d) ///< 0.65 * 2^RATIO_SCALE -#define TSL2561_LUX_B5C (0x0177) ///< 0.0229 * 2^LUX_SCALE -#define TSL2561_LUX_M5C (0x01dd) ///< 0.0291 * 2^LUX_SCALE -#define TSL2561_LUX_K6C (0x019a) ///< 0.80 * 2^RATIO_SCALE -#define TSL2561_LUX_B6C (0x0101) ///< 0.0157 * 2^LUX_SCALE -#define TSL2561_LUX_M6C (0x0127) ///< 0.0180 * 2^LUX_SCALE -#define TSL2561_LUX_K7C (0x029a) ///< 1.3 * 2^RATIO_SCALE -#define TSL2561_LUX_B7C (0x0037) ///< 0.00338 * 2^LUX_SCALE -#define TSL2561_LUX_M7C (0x002b) ///< 0.00260 * 2^LUX_SCALE -#define TSL2561_LUX_K8C (0x029a) ///< 1.3 * 2^RATIO_SCALE -#define TSL2561_LUX_B8C (0x0000) ///< 0.000 * 2^LUX_SCALE -#define TSL2561_LUX_M8C (0x0000) ///< 0.000 * 2^LUX_SCALE - -// Auto-gain thresholds -#define TSL2561_AGC_THI_13MS (4850) ///< Max value at Ti 13ms = 5047 -#define TSL2561_AGC_TLO_13MS (100) ///< Min value at Ti 13ms = 100 -#define TSL2561_AGC_THI_101MS (36000) ///< Max value at Ti 101ms = 37177 -#define TSL2561_AGC_TLO_101MS (200) ///< Min value at Ti 101ms = 200 -#define TSL2561_AGC_THI_402MS (63000) ///< Max value at Ti 402ms = 65535 -#define TSL2561_AGC_TLO_402MS (500) ///< Min value at Ti 402ms = 500 - -// Clipping thresholds -#define TSL2561_CLIPPING_13MS (4900) ///< # Counts that trigger a change in gain/integration -#define TSL2561_CLIPPING_101MS (37000) ///< # Counts that trigger a change in gain/integration -#define TSL2561_CLIPPING_402MS (65000) ///< # Counts that trigger a change in gain/integration - -// Delay for integration times -#define TSL2561_DELAY_INTTIME_13MS (15) ///< Wait 15ms for 13ms integration -#define TSL2561_DELAY_INTTIME_101MS (120) ///< Wait 120ms for 101ms integration -#define TSL2561_DELAY_INTTIME_402MS (450) ///< Wait 450ms for 402ms integration - -/** TSL2561 I2C Registers */ -enum -{ - TSL2561_REGISTER_CONTROL = 0x00, // Control/power register - TSL2561_REGISTER_TIMING = 0x01, // Set integration time register - TSL2561_REGISTER_THRESHHOLDL_LOW = 0x02, // Interrupt low threshold low-byte - TSL2561_REGISTER_THRESHHOLDL_HIGH = 0x03, // Interrupt low threshold high-byte - TSL2561_REGISTER_THRESHHOLDH_LOW = 0x04, // Interrupt high threshold low-byte - TSL2561_REGISTER_THRESHHOLDH_HIGH = 0x05, // Interrupt high threshold high-byte - TSL2561_REGISTER_INTERRUPT = 0x06, // Interrupt settings - TSL2561_REGISTER_CRC = 0x08, // Factory use only - TSL2561_REGISTER_ID = 0x0A, // TSL2561 identification setting - TSL2561_REGISTER_CHAN0_LOW = 0x0C, // Light data channel 0, low byte - TSL2561_REGISTER_CHAN0_HIGH = 0x0D, // Light data channel 0, high byte - TSL2561_REGISTER_CHAN1_LOW = 0x0E, // Light data channel 1, low byte - TSL2561_REGISTER_CHAN1_HIGH = 0x0F // Light data channel 1, high byte -}; - -/** Three options for how long to integrate readings for */ -typedef enum -{ - TSL2561_INTEGRATIONTIME_13MS = 0x00, // 13.7ms - TSL2561_INTEGRATIONTIME_101MS = 0x01, // 101ms - TSL2561_INTEGRATIONTIME_402MS = 0x02 // 402ms -} -tsl2561IntegrationTime_t; - -/** TSL2561 offers 2 gain settings */ -typedef enum -{ - TSL2561_GAIN_1X = 0x00, // No gain - TSL2561_GAIN_16X = 0x10, // 16x gain -} -tsl2561Gain_t; - - - -/**************************************************************************/ -/*! - @brief Class that stores state and functions for interacting with TSL2561 Light Sensor -*/ -/**************************************************************************/ -class Adafruit_TSL2561_Unified : public Adafruit_Sensor { - public: - Adafruit_TSL2561_Unified(uint8_t addr, int32_t sensorID = -1); - boolean begin(void); - boolean begin(TwoWire *theWire); - boolean init(); - - /* TSL2561 Functions */ - void enableAutoRange(bool enable); - void setIntegrationTime(tsl2561IntegrationTime_t time); - void setGain(tsl2561Gain_t gain); - void getLuminosity (uint16_t *broadband, uint16_t *ir); - uint32_t calculateLux(uint16_t broadband, uint16_t ir); - - /* Unified Sensor API Functions */ - bool getEvent(sensors_event_t*); - void getSensor(sensor_t*); - - private: - TwoWire *_i2c; - - int8_t _addr; - boolean _tsl2561Initialised; - boolean _tsl2561AutoGain; - tsl2561IntegrationTime_t _tsl2561IntegrationTime; - tsl2561Gain_t _tsl2561Gain; - int32_t _tsl2561SensorID; - - void enable (void); - void disable (void); - void write8 (uint8_t reg, uint8_t value); - uint8_t read8 (uint8_t reg); - uint16_t read16 (uint8_t reg); - void getData (uint16_t *broadband, uint16_t *ir); -}; - -#endif // ADAFRUIT_TSL2561_H diff --git a/lib/Adafruit_TSL2561/README.md b/lib/Adafruit_TSL2561/README.md deleted file mode 100644 index 87dd30f4..00000000 --- a/lib/Adafruit_TSL2561/README.md +++ /dev/null @@ -1,50 +0,0 @@ -# Adafruit TSL2561 Light Sensor Driver [![Build Status](https://travis-ci.org/adafruit/Adafruit_TSL2561.svg?branch=master)](https://travis-ci.org/adafruit/Adafruit_TSL2561) - -This driver is for the Adafruit TSL2561 Breakout, and is based on Adafruit's Unified Sensor Library (Adafruit_Sensor). - - - - -The driver supports manual or 'auto' gain. Adjusting the gain allows you to make the sensor more or less 'sensitive' to light (depending on if you are indoors or outdoors, for example): -``` -tsl.setGain(TSL2561_GAIN_1X); /* No gain ... use in bright light to avoid sensor saturation */ -tsl.setGain(TSL2561_GAIN_16X); /* 16x gain ... use in low light to boost sensitivity */ -tsl.enableAutoGain(true); /* Auto-gain ... switches automatically between 1x and 16x */ -``` - -The driver also supports as automatic clipping detection, and will return '65536' lux when the sensor is saturated and data is unreliable. tsl.getEvent will return false in case of saturation and true in case of valid light data. - -## About the TSL2561 ## - -The TSL2561 is a 16-bit digital (I2C) light sensor, with adjustable gain and 'integration time'. - -Adjusting the 'integration time' essentially increases the resolution of the device, since the analog converter inside the chip has time to take more samples. The integration time can be set as follows: -``` -tsl.setIntegrationTime(TSL2561_INTEGRATIONTIME_13MS); /* fast but low resolution */ -tsl.setIntegrationTime(TSL2561_INTEGRATIONTIME_101MS); /* medium resolution and speed */ -tsl.setIntegrationTime(TSL2561_INTEGRATIONTIME_402MS); /* 16-bit data but slowest conversions */ -``` - -One of the big advantages of the TSL2561 is that it is capable of measuring both broadband (visible plus infrared) and infrared light thanks to two distinct sensing units on the device. This is important in certain lighting environments to be able to read the light level reliably. - -More information on the TSL2561 can be found in the datasheet: http://www.adafruit.com/datasheets/TSL2561.pdf - -## What is the Adafruit Unified Sensor Library? ## - -The Adafruit Unified Sensor Library (Adafruit_Sensor) provides a common interface and data type for any supported sensor. It defines some basic information about the sensor (sensor limits, etc.), and returns standard SI units of a specific type and scale for each supported sensor type. - -It provides a simple abstraction layer between your application and the actual sensor HW, allowing you to drop in any comparable sensor with only one or two lines of code to change in your project (essentially the constructor since the functions to read sensor data and get information about the sensor are defined in the base Adafruit_Sensor class). - -This is imporant useful for two reasons: - -1.) You can use the data right away because it's already converted to SI units that you understand and can compare, rather than meaningless values like 0..1023. - -2.) Because SI units are standardised in the sensor library, you can also do quick sanity checks working with new sensors, or drop in any comparable sensor if you need better sensitivity or if a lower cost unit becomes available, etc. - -Light sensors will always report units in lux, gyroscopes will always report units in rad/s, etc. ... freeing you up to focus on the data, rather than digging through the datasheet to understand what the sensor's raw numbers really mean. - -## About this Driver ## - -Adafruit invests time and resources providing this open source code. Please support Adafruit and open-source hardware by purchasing products from Adafruit! - -Written by Kevin (KTOWN) Townsend for Adafruit Industries. diff --git a/lib/Adafruit_TSL2561/examples/sensorapi/sensorapi.ino b/lib/Adafruit_TSL2561/examples/sensorapi/sensorapi.ino deleted file mode 100644 index 665d579e..00000000 --- a/lib/Adafruit_TSL2561/examples/sensorapi/sensorapi.ino +++ /dev/null @@ -1,140 +0,0 @@ -#include -#include -#include - -/* This driver uses the Adafruit unified sensor library (Adafruit_Sensor), - which provides a common 'type' for sensor data and some helper functions. - - To use this driver you will also need to download the Adafruit_Sensor - library and include it in your libraries folder. - - You should also assign a unique ID to this sensor for use with - the Adafruit Sensor API so that you can identify this particular - sensor in any data logs, etc. To assign a unique ID, simply - provide an appropriate value in the constructor below (12345 - is used by default in this example). - - Connections - =========== - Connect SCL to I2C SCL Clock - Connect SDA to I2C SDA Data - Connect VDD to 3.3V or 5V (whatever your logic level is) - Connect GROUND to common ground - - I2C Address - =========== - The address will be different depending on whether you leave - the ADDR pin floating (addr 0x39), or tie it to ground or vcc. - The default addess is 0x39, which assumes the ADDR pin is floating - (not connected to anything). If you set the ADDR pin high - or low, use TSL2561_ADDR_HIGH (0x49) or TSL2561_ADDR_LOW - (0x29) respectively. - - History - ======= - 2013/JAN/31 - First version (KTOWN) -*/ - -Adafruit_TSL2561_Unified tsl = Adafruit_TSL2561_Unified(TSL2561_ADDR_FLOAT, 12345); - -/**************************************************************************/ -/* - Displays some basic information on this sensor from the unified - sensor API sensor_t type (see Adafruit_Sensor for more information) -*/ -/**************************************************************************/ -void displaySensorDetails(void) -{ - sensor_t sensor; - tsl.getSensor(&sensor); - Serial.println("------------------------------------"); - Serial.print ("Sensor: "); Serial.println(sensor.name); - Serial.print ("Driver Ver: "); Serial.println(sensor.version); - Serial.print ("Unique ID: "); Serial.println(sensor.sensor_id); - Serial.print ("Max Value: "); Serial.print(sensor.max_value); Serial.println(" lux"); - Serial.print ("Min Value: "); Serial.print(sensor.min_value); Serial.println(" lux"); - Serial.print ("Resolution: "); Serial.print(sensor.resolution); Serial.println(" lux"); - Serial.println("------------------------------------"); - Serial.println(""); - delay(500); -} - -/**************************************************************************/ -/* - Configures the gain and integration time for the TSL2561 -*/ -/**************************************************************************/ -void configureSensor(void) -{ - /* You can also manually set the gain or enable auto-gain support */ - // tsl.setGain(TSL2561_GAIN_1X); /* No gain ... use in bright light to avoid sensor saturation */ - // tsl.setGain(TSL2561_GAIN_16X); /* 16x gain ... use in low light to boost sensitivity */ - tsl.enableAutoRange(true); /* Auto-gain ... switches automatically between 1x and 16x */ - - /* Changing the integration time gives you better sensor resolution (402ms = 16-bit data) */ - tsl.setIntegrationTime(TSL2561_INTEGRATIONTIME_13MS); /* fast but low resolution */ - // tsl.setIntegrationTime(TSL2561_INTEGRATIONTIME_101MS); /* medium resolution and speed */ - // tsl.setIntegrationTime(TSL2561_INTEGRATIONTIME_402MS); /* 16-bit data but slowest conversions */ - - /* Update these values depending on what you've set above! */ - Serial.println("------------------------------------"); - Serial.print ("Gain: "); Serial.println("Auto"); - Serial.print ("Timing: "); Serial.println("13 ms"); - Serial.println("------------------------------------"); -} - -/**************************************************************************/ -/* - Arduino setup function (automatically called at startup) -*/ -/**************************************************************************/ -void setup(void) -{ - Serial.begin(9600); - Serial.println("Light Sensor Test"); Serial.println(""); - - /* Initialise the sensor */ - //use tsl.begin() to default to Wire, - //tsl.begin(&Wire2) directs api to use Wire2, etc. - if(!tsl.begin()) - { - /* There was a problem detecting the TSL2561 ... check your connections */ - Serial.print("Ooops, no TSL2561 detected ... Check your wiring or I2C ADDR!"); - while(1); - } - - /* Display some basic information on this sensor */ - displaySensorDetails(); - - /* Setup the sensor gain and integration time */ - configureSensor(); - - /* We're ready to go! */ - Serial.println(""); -} - -/**************************************************************************/ -/* - Arduino loop function, called once 'setup' is complete (your own code - should go here) -*/ -/**************************************************************************/ -void loop(void) -{ - /* Get a new sensor event */ - sensors_event_t event; - tsl.getEvent(&event); - - /* Display the results (light is measured in lux) */ - if (event.light) - { - Serial.print(event.light); Serial.println(" lux"); - } - else - { - /* If event.light = 0 lux the sensor is probably saturated - and no reliable data could be generated! */ - Serial.println("Sensor overload"); - } - delay(250); -} diff --git a/lib/Adafruit_TSL2561/library.properties b/lib/Adafruit_TSL2561/library.properties deleted file mode 100644 index 7656b9da..00000000 --- a/lib/Adafruit_TSL2561/library.properties +++ /dev/null @@ -1,9 +0,0 @@ -name=Adafruit TSL2561 -version=1.0.2 -author=Adafruit -maintainer=Adafruit -sentence=Unified sensor driver for Adafruit's TSL2561 breakouts -paragraph=Unified sensor driver for Adafruit's TSL2561 breakouts -category=Sensors -url=https://github.com/adafruit/Adafruit_TSL2561 -architectures=* diff --git a/lib/Arduino-INA226/CHANGELOG b/lib/Arduino-INA226/CHANGELOG deleted file mode 100644 index ea34876f..00000000 --- a/lib/Arduino-INA226/CHANGELOG +++ /dev/null @@ -1,4 +0,0 @@ -INA226 Arduino Library 1.0.0 / 08.04.2014 -====================================================================== - - * First release diff --git a/lib/Arduino-INA226/INA226.cpp b/lib/Arduino-INA226/INA226.cpp deleted file mode 100644 index 3d37acaa..00000000 --- a/lib/Arduino-INA226/INA226.cpp +++ /dev/null @@ -1,332 +0,0 @@ -/* -INA226.cpp - Class file for the INA226 Bi-directional Current/Power Monitor Arduino Library. - -Version: 1.0.0 -(c) 2014 Korneliusz Jarzebski -www.jarzebski.pl - -This program is free software: you can redistribute it and/or modify -it under the terms of the version 3 GNU General Public License as -published by the Free Software Foundation. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program. If not, see . -*/ - -#if ARDUINO >= 100 -#include "Arduino.h" -#else -#include "WProgram.h" -#endif - -#include - -#include "INA226.h" - -bool INA226::begin(uint8_t address) -{ - Wire.begin(); - inaAddress = address; - return true; -} - -bool INA226::configure(ina226_averages_t avg, ina226_busConvTime_t busConvTime, ina226_shuntConvTime_t shuntConvTime, ina226_mode_t mode) -{ - uint16_t config = 0; - - config |= (avg << 9 | busConvTime << 6 | shuntConvTime << 3 | mode); - - vBusMax = 36; - vShuntMax = 0.08192f; - - writeRegister16(INA226_REG_CONFIG, config); - - return true; -} - -bool INA226::calibrate(float rShuntValue, float iMaxExpected) -{ - uint16_t calibrationValue; - rShunt = rShuntValue; - - float iMaxPossible, minimumLSB; - - iMaxPossible = vShuntMax / rShunt; - - minimumLSB = iMaxExpected / 32767; - - currentLSB = (uint16_t)(minimumLSB * 100000000); - currentLSB /= 100000000; - currentLSB /= 0.0001; - currentLSB = ceil(currentLSB); - currentLSB *= 0.0001; - - powerLSB = currentLSB * 25; - - calibrationValue = (uint16_t)((0.00512) / (currentLSB * rShunt)); - - writeRegister16(INA226_REG_CALIBRATION, calibrationValue); - - return true; -} - -float INA226::getMaxPossibleCurrent(void) -{ - return (vShuntMax / rShunt); -} - -float INA226::getMaxCurrent(void) -{ - float maxCurrent = (currentLSB * 32767); - float maxPossible = getMaxPossibleCurrent(); - - if (maxCurrent > maxPossible) - { - return maxPossible; - } else - { - return maxCurrent; - } -} - -float INA226::getMaxShuntVoltage(void) -{ - float maxVoltage = getMaxCurrent() * rShunt; - - if (maxVoltage >= vShuntMax) - { - return vShuntMax; - } else - { - return maxVoltage; - } -} - -float INA226::getMaxPower(void) -{ - return (getMaxCurrent() * vBusMax); -} - -float INA226::readBusPower(void) -{ - return (readRegister16(INA226_REG_POWER) * powerLSB); -} - -float INA226::readShuntCurrent(void) -{ - return (readRegister16(INA226_REG_CURRENT) * currentLSB); -} - -float INA226::readShuntVoltage(void) -{ - float voltage; - - voltage = readRegister16(INA226_REG_SHUNTVOLTAGE); - - return (voltage * 0.0000025); -} - -float INA226::readBusVoltage(void) -{ - int16_t voltage; - - voltage = readRegister16(INA226_REG_BUSVOLTAGE); - - return (voltage * 0.00125); -} - -ina226_averages_t INA226::getAverages(void) -{ - uint16_t value; - - value = readRegister16(INA226_REG_CONFIG); - value &= 0b0000111000000000; - value >>= 9; - - return (ina226_averages_t)value; -} - -ina226_busConvTime_t INA226::getBusConversionTime(void) -{ - uint16_t value; - - value = readRegister16(INA226_REG_CONFIG); - value &= 0b0000000111000000; - value >>= 6; - - return (ina226_busConvTime_t)value; -} - -ina226_shuntConvTime_t INA226::getShuntConversionTime(void) -{ - uint16_t value; - - value = readRegister16(INA226_REG_CONFIG); - value &= 0b0000000000111000; - value >>= 3; - - return (ina226_shuntConvTime_t)value; -} - -ina226_mode_t INA226::getMode(void) -{ - uint16_t value; - - value = readRegister16(INA226_REG_CONFIG); - value &= 0b0000000000000111; - - return (ina226_mode_t)value; -} - -void INA226::setMaskEnable(uint16_t mask) -{ - writeRegister16(INA226_REG_MASKENABLE, mask); -} - -uint16_t INA226::getMaskEnable(void) -{ - return readRegister16(INA226_REG_MASKENABLE); -} - -void INA226::enableShuntOverLimitAlert(void) -{ - writeRegister16(INA226_REG_MASKENABLE, INA226_BIT_SOL); -} - -void INA226::enableShuntUnderLimitAlert(void) -{ - writeRegister16(INA226_REG_MASKENABLE, INA226_BIT_SUL); -} - -void INA226::enableBusOvertLimitAlert(void) -{ - writeRegister16(INA226_REG_MASKENABLE, INA226_BIT_BOL); -} - -void INA226::enableBusUnderLimitAlert(void) -{ - writeRegister16(INA226_REG_MASKENABLE, INA226_BIT_BUL); -} - -void INA226::enableOverPowerLimitAlert(void) -{ - writeRegister16(INA226_REG_MASKENABLE, INA226_BIT_POL); -} - -void INA226::enableConversionReadyAlert(void) -{ - writeRegister16(INA226_REG_MASKENABLE, INA226_BIT_CNVR); -} - -void INA226::setBusVoltageLimit(float voltage) -{ - uint16_t value = voltage / 0.00125; - writeRegister16(INA226_REG_ALERTLIMIT, value); -} - -void INA226::setShuntVoltageLimit(float voltage) -{ - uint16_t value = voltage * 25000; - writeRegister16(INA226_REG_ALERTLIMIT, value); -} - -void INA226::setPowerLimit(float watts) -{ - uint16_t value = watts / powerLSB; - writeRegister16(INA226_REG_ALERTLIMIT, value); -} - -void INA226::setAlertInvertedPolarity(bool inverted) -{ - uint16_t temp = getMaskEnable(); - - if (inverted) - { - temp |= INA226_BIT_APOL; - } else - { - temp &= ~INA226_BIT_APOL; - } - - setMaskEnable(temp); -} - -void INA226::setAlertLatch(bool latch) -{ - uint16_t temp = getMaskEnable(); - - if (latch) - { - temp |= INA226_BIT_LEN; - } else - { - temp &= ~INA226_BIT_LEN; - } - - setMaskEnable(temp); -} - -bool INA226::isMathOverflow(void) -{ - return ((getMaskEnable() & INA226_BIT_OVF) == INA226_BIT_OVF); -} - -bool INA226::isAlert(void) -{ - return ((getMaskEnable() & INA226_BIT_AFF) == INA226_BIT_AFF); -} - -int16_t INA226::readRegister16(uint8_t reg) -{ - int16_t value; - - Wire.beginTransmission(inaAddress); - #if ARDUINO >= 100 - Wire.write(reg); - #else - Wire.send(reg); - #endif - Wire.endTransmission(); - - delay(1); - - Wire.beginTransmission(inaAddress); - Wire.requestFrom(inaAddress, 2); - while(!Wire.available()) {}; - #if ARDUINO >= 100 - uint8_t vha = Wire.read(); - uint8_t vla = Wire.read(); - #else - uint8_t vha = Wire.receive(); - uint8_t vla = Wire.receive(); - #endif; - Wire.endTransmission(); - - value = vha << 8 | vla; - - return value; -} - -void INA226::writeRegister16(uint8_t reg, uint16_t val) -{ - uint8_t vla; - vla = (uint8_t)val; - val >>= 8; - - Wire.beginTransmission(inaAddress); - #if ARDUINO >= 100 - Wire.write(reg); - Wire.write((uint8_t)val); - Wire.write(vla); - #else - Wire.send(reg); - Wire.send((uint8_t)val); - Wire.send(vla); - #endif - Wire.endTransmission(); -} diff --git a/lib/Arduino-INA226/INA226.h b/lib/Arduino-INA226/INA226.h deleted file mode 100644 index 241c3606..00000000 --- a/lib/Arduino-INA226/INA226.h +++ /dev/null @@ -1,154 +0,0 @@ -/* -INA226.h - Header file for the Bi-directional Current/Power Monitor Arduino Library. - -Version: 1.0.0 -(c) 2014 Korneliusz Jarzebski -www.jarzebski.pl - -This program is free software: you can redistribute it and/or modify -it under the terms of the version 3 GNU General Public License as -published by the Free Software Foundation. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program. If not, see . -*/ - -#ifndef INA226_h -#define INA226_h - -#if ARDUINO >= 100 -#include "Arduino.h" -#else -#include "WProgram.h" -#endif - -#define INA226_ADDRESS (0x40) - -#define INA226_REG_CONFIG (0x00) -#define INA226_REG_SHUNTVOLTAGE (0x01) -#define INA226_REG_BUSVOLTAGE (0x02) -#define INA226_REG_POWER (0x03) -#define INA226_REG_CURRENT (0x04) -#define INA226_REG_CALIBRATION (0x05) -#define INA226_REG_MASKENABLE (0x06) -#define INA226_REG_ALERTLIMIT (0x07) - -#define INA226_BIT_SOL (0x8000) -#define INA226_BIT_SUL (0x4000) -#define INA226_BIT_BOL (0x2000) -#define INA226_BIT_BUL (0x1000) -#define INA226_BIT_POL (0x0800) -#define INA226_BIT_CNVR (0x0400) -#define INA226_BIT_AFF (0x0010) -#define INA226_BIT_CVRF (0x0008) -#define INA226_BIT_OVF (0x0004) -#define INA226_BIT_APOL (0x0002) -#define INA226_BIT_LEN (0x0001) - -typedef enum -{ - INA226_AVERAGES_1 = 0b000, - INA226_AVERAGES_4 = 0b001, - INA226_AVERAGES_16 = 0b010, - INA226_AVERAGES_64 = 0b011, - INA226_AVERAGES_128 = 0b100, - INA226_AVERAGES_256 = 0b101, - INA226_AVERAGES_512 = 0b110, - INA226_AVERAGES_1024 = 0b111 -} ina226_averages_t; - -typedef enum -{ - INA226_BUS_CONV_TIME_140US = 0b000, - INA226_BUS_CONV_TIME_204US = 0b001, - INA226_BUS_CONV_TIME_332US = 0b010, - INA226_BUS_CONV_TIME_588US = 0b011, - INA226_BUS_CONV_TIME_1100US = 0b100, - INA226_BUS_CONV_TIME_2116US = 0b101, - INA226_BUS_CONV_TIME_4156US = 0b110, - INA226_BUS_CONV_TIME_8244US = 0b111 -} ina226_busConvTime_t; - -typedef enum -{ - INA226_SHUNT_CONV_TIME_140US = 0b000, - INA226_SHUNT_CONV_TIME_204US = 0b001, - INA226_SHUNT_CONV_TIME_332US = 0b010, - INA226_SHUNT_CONV_TIME_588US = 0b011, - INA226_SHUNT_CONV_TIME_1100US = 0b100, - INA226_SHUNT_CONV_TIME_2116US = 0b101, - INA226_SHUNT_CONV_TIME_4156US = 0b110, - INA226_SHUNT_CONV_TIME_8244US = 0b111 -} ina226_shuntConvTime_t; - -typedef enum -{ - INA226_MODE_POWER_DOWN = 0b000, - INA226_MODE_SHUNT_TRIG = 0b001, - INA226_MODE_BUS_TRIG = 0b010, - INA226_MODE_SHUNT_BUS_TRIG = 0b011, - INA226_MODE_ADC_OFF = 0b100, - INA226_MODE_SHUNT_CONT = 0b101, - INA226_MODE_BUS_CONT = 0b110, - INA226_MODE_SHUNT_BUS_CONT = 0b111, -} ina226_mode_t; - -class INA226 -{ - public: - - bool begin(uint8_t address = INA226_ADDRESS); - bool configure(ina226_averages_t avg = INA226_AVERAGES_1, ina226_busConvTime_t busConvTime = INA226_BUS_CONV_TIME_1100US, ina226_shuntConvTime_t shuntConvTime = INA226_SHUNT_CONV_TIME_1100US, ina226_mode_t mode = INA226_MODE_SHUNT_BUS_CONT); - bool calibrate(float rShuntValue = 0.1, float iMaxExcepted = 2); - - ina226_averages_t getAverages(void); - ina226_busConvTime_t getBusConversionTime(void); - ina226_shuntConvTime_t getShuntConversionTime(void); - ina226_mode_t getMode(void); - - void enableShuntOverLimitAlert(void); - void enableShuntUnderLimitAlert(void); - void enableBusOvertLimitAlert(void); - void enableBusUnderLimitAlert(void); - void enableOverPowerLimitAlert(void); - void enableConversionReadyAlert(void); - - void setBusVoltageLimit(float voltage); - void setShuntVoltageLimit(float voltage); - void setPowerLimit(float watts); - - void setAlertInvertedPolarity(bool inverted); - void setAlertLatch(bool latch); - - bool isMathOverflow(void); - bool isAlert(void); - - float readShuntCurrent(void); - float readShuntVoltage(void); - float readBusPower(void); - float readBusVoltage(void); - - float getMaxPossibleCurrent(void); - float getMaxCurrent(void); - float getMaxShuntVoltage(void); - float getMaxPower(void); - - private: - - int8_t inaAddress; - float currentLSB, powerLSB; - float vShuntMax, vBusMax, rShunt; - - void setMaskEnable(uint16_t mask); - uint16_t getMaskEnable(void); - - void writeRegister16(uint8_t reg, uint16_t val); - int16_t readRegister16(uint8_t reg); -}; - -#endif \ No newline at end of file diff --git a/lib/Arduino-INA226/INA226_alert/INA226_alert.ino b/lib/Arduino-INA226/INA226_alert/INA226_alert.ino deleted file mode 100644 index d1719194..00000000 --- a/lib/Arduino-INA226/INA226_alert/INA226_alert.ino +++ /dev/null @@ -1,67 +0,0 @@ -/* - INA226 Bi-directional Current/Power Monitor. Alert Example. - Read more: http://www.jarzebski.pl/arduino/czujniki-i-sensory/cyfrowy-czujnik-pradu-mocy-ina226.html - GIT: https://github.com/jarzebski/Arduino-INA226 - Web: http://www.jarzebski.pl - (c) 2014 by Korneliusz Jarzebski -*/ - -#include -#include - -INA226 ina; - -void setup() -{ - Serial.begin(115200); - - Serial.println("Initialize INA226"); - Serial.println("-----------------------------------------------"); - - // Default INA226 address is 0x40 - ina.begin(); - - // Configure INA226 - ina.configure(INA226_AVERAGES_1, INA226_BUS_CONV_TIME_1100US, INA226_SHUNT_CONV_TIME_1100US, INA226_MODE_SHUNT_BUS_CONT); - - // Calibrate INA226. Rshunt = 0.01 ohm, Max excepted current = 4A - ina.calibrate(0.01, 4); - - // Enable Bus Over-Voltage Alert - // ina.enableBusOvertLimitAlert(); - // ina.enableBusUnderLimitAlert(); - // ina.setBusVoltageLimit(3.33); - - // Enable Shunt Over-Voltage Alert - // ina.enableShuntOverLimitAlert(); - // ina.enableShuntUnderLimitAlert(); - // ina.setShuntVoltageLimit(0.0055); - - // Enable Power Over-Limit Alert - ina.enableOverPowerLimitAlert(); - ina.setPowerLimit(0.130); - - // ina.setAlertInvertedPolarity(true) -} - -void loop() -{ - Serial.print("Bus voltage: "); - Serial.print(ina.readBusVoltage(), 5); - Serial.println(" V"); - - Serial.print("Bus power: "); - Serial.print(ina.readBusPower(), 5); - Serial.println(" W"); - - Serial.print("Shunt voltage: "); - Serial.print(ina.readShuntVoltage(), 5); - Serial.println(" V"); - - Serial.print("Shunt current: "); - Serial.print(ina.readShuntCurrent(), 5); - Serial.println(" A"); - - Serial.println(""); - delay(1000); -} diff --git a/lib/Arduino-INA226/INA226_latch/INA226_latch.ino b/lib/Arduino-INA226/INA226_latch/INA226_latch.ino deleted file mode 100644 index 1e168552..00000000 --- a/lib/Arduino-INA226/INA226_latch/INA226_latch.ino +++ /dev/null @@ -1,64 +0,0 @@ -/* - INA226 Bi-directional Current/Power Monitor. Alert with latch Example. - Read more: http://www.jarzebski.pl/arduino/czujniki-i-sensory/cyfrowy-czujnik-pradu-mocy-ina226.html - GIT: https://github.com/jarzebski/Arduino-INA226 - Web: http://www.jarzebski.pl - (c) 2014 by Korneliusz Jarzebski - */ - -#include -#include - -INA226 ina; - -void setup() -{ - Serial.begin(115200); - - Serial.println("Initialize INA226"); - Serial.println("-----------------------------------------------"); - - // Default INA226 address is 0x40 - ina.begin(); - - // Configure INA226 - ina.configure(INA226_AVERAGES_1, INA226_BUS_CONV_TIME_1100US, INA226_SHUNT_CONV_TIME_1100US, INA226_MODE_SHUNT_BUS_CONT); - - // Calibrate INA226. Rshunt = 0.01 ohm, Max excepted current = 4A - ina.calibrate(0.01, 4); - - // Enable Power Over-Limit Alert - ina.enableOverPowerLimitAlert(); - ina.setPowerLimit(0.130); - ina.setAlertLatch(true); -} - -void loop() -{ - Serial.print("Bus voltage: "); - Serial.print(ina.readBusVoltage(), 5); - Serial.println(" V"); - - Serial.print("Bus power: "); - Serial.print(ina.readBusPower(), 5); - Serial.println(" W"); - - - Serial.print("Shunt voltage: "); - Serial.print(ina.readShuntVoltage(), 5); - Serial.println(" V"); - - Serial.print("Shunt current: "); - Serial.print(ina.readShuntCurrent(), 5); - Serial.println(" A"); - - if (ina.isAlert()) - { - // Latch will be removed here - Serial.println("ALERT"); - } - - Serial.println(""); - delay(1000); -} - diff --git a/lib/Arduino-INA226/INA226_simple/INA226_simple.ino b/lib/Arduino-INA226/INA226_simple/INA226_simple.ino deleted file mode 100644 index 1bada92f..00000000 --- a/lib/Arduino-INA226/INA226_simple/INA226_simple.ino +++ /dev/null @@ -1,132 +0,0 @@ -/* - INA226 Bi-directional Current/Power Monitor. Simple Example. - Read more: http://www.jarzebski.pl/arduino/czujniki-i-sensory/cyfrowy-czujnik-pradu-mocy-ina226.html - GIT: https://github.com/jarzebski/Arduino-INA226 - Web: http://www.jarzebski.pl - (c) 2014 by Korneliusz Jarzebski -*/ - -#include -#include - -INA226 ina; - -void checkConfig() -{ - Serial.print("Mode: "); - switch (ina.getMode()) - { - case INA226_MODE_POWER_DOWN: Serial.println("Power-Down"); break; - case INA226_MODE_SHUNT_TRIG: Serial.println("Shunt Voltage, Triggered"); break; - case INA226_MODE_BUS_TRIG: Serial.println("Bus Voltage, Triggered"); break; - case INA226_MODE_SHUNT_BUS_TRIG: Serial.println("Shunt and Bus, Triggered"); break; - case INA226_MODE_ADC_OFF: Serial.println("ADC Off"); break; - case INA226_MODE_SHUNT_CONT: Serial.println("Shunt Voltage, Continuous"); break; - case INA226_MODE_BUS_CONT: Serial.println("Bus Voltage, Continuous"); break; - case INA226_MODE_SHUNT_BUS_CONT: Serial.println("Shunt and Bus, Continuous"); break; - default: Serial.println("unknown"); - } - - Serial.print("Samples average: "); - switch (ina.getAverages()) - { - case INA226_AVERAGES_1: Serial.println("1 sample"); break; - case INA226_AVERAGES_4: Serial.println("4 samples"); break; - case INA226_AVERAGES_16: Serial.println("16 samples"); break; - case INA226_AVERAGES_64: Serial.println("64 samples"); break; - case INA226_AVERAGES_128: Serial.println("128 samples"); break; - case INA226_AVERAGES_256: Serial.println("256 samples"); break; - case INA226_AVERAGES_512: Serial.println("512 samples"); break; - case INA226_AVERAGES_1024: Serial.println("1024 samples"); break; - default: Serial.println("unknown"); - } - - Serial.print("Bus conversion time: "); - switch (ina.getBusConversionTime()) - { - case INA226_BUS_CONV_TIME_140US: Serial.println("140uS"); break; - case INA226_BUS_CONV_TIME_204US: Serial.println("204uS"); break; - case INA226_BUS_CONV_TIME_332US: Serial.println("332uS"); break; - case INA226_BUS_CONV_TIME_588US: Serial.println("558uS"); break; - case INA226_BUS_CONV_TIME_1100US: Serial.println("1.100ms"); break; - case INA226_BUS_CONV_TIME_2116US: Serial.println("2.116ms"); break; - case INA226_BUS_CONV_TIME_4156US: Serial.println("4.156ms"); break; - case INA226_BUS_CONV_TIME_8244US: Serial.println("8.244ms"); break; - default: Serial.println("unknown"); - } - - Serial.print("Shunt conversion time: "); - switch (ina.getShuntConversionTime()) - { - case INA226_SHUNT_CONV_TIME_140US: Serial.println("140uS"); break; - case INA226_SHUNT_CONV_TIME_204US: Serial.println("204uS"); break; - case INA226_SHUNT_CONV_TIME_332US: Serial.println("332uS"); break; - case INA226_SHUNT_CONV_TIME_588US: Serial.println("558uS"); break; - case INA226_SHUNT_CONV_TIME_1100US: Serial.println("1.100ms"); break; - case INA226_SHUNT_CONV_TIME_2116US: Serial.println("2.116ms"); break; - case INA226_SHUNT_CONV_TIME_4156US: Serial.println("4.156ms"); break; - case INA226_SHUNT_CONV_TIME_8244US: Serial.println("8.244ms"); break; - default: Serial.println("unknown"); - } - - Serial.print("Max possible current: "); - Serial.print(ina.getMaxPossibleCurrent()); - Serial.println(" A"); - - Serial.print("Max current: "); - Serial.print(ina.getMaxCurrent()); - Serial.println(" A"); - - Serial.print("Max shunt voltage: "); - Serial.print(ina.getMaxShuntVoltage()); - Serial.println(" V"); - - Serial.print("Max power: "); - Serial.print(ina.getMaxPower()); - Serial.println(" W"); -} - -void setup() -{ - Serial.begin(115200); - - Serial.println("Initialize INA226"); - Serial.println("-----------------------------------------------"); - - // Default INA226 address is 0x40 - ina.begin(); - - // Configure INA226 - ina.configure(INA226_AVERAGES_1, INA226_BUS_CONV_TIME_1100US, INA226_SHUNT_CONV_TIME_1100US, INA226_MODE_SHUNT_BUS_CONT); - - // Calibrate INA226. Rshunt = 0.01 ohm, Max excepted current = 4A - ina.calibrate(0.01, 4); - - // Display configuration - checkConfig(); - - Serial.println("-----------------------------------------------"); -} - -void loop() -{ - Serial.print("Bus voltage: "); - Serial.print(ina.readBusVoltage(), 5); - Serial.println(" V"); - - Serial.print("Bus power: "); - Serial.print(ina.readBusPower(), 5); - Serial.println(" W"); - - - Serial.print("Shunt voltage: "); - Serial.print(ina.readShuntVoltage(), 5); - Serial.println(" V"); - - Serial.print("Shunt current: "); - Serial.print(ina.readShuntCurrent(), 5); - Serial.println(" A"); - - Serial.println(""); - delay(1000); -} diff --git a/lib/Arduino-INA226/LICENSE b/lib/Arduino-INA226/LICENSE deleted file mode 100644 index ef7e7efc..00000000 --- a/lib/Arduino-INA226/LICENSE +++ /dev/null @@ -1,674 +0,0 @@ -GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - {one line to give the program's name and a brief idea of what it does.} - Copyright (C) {year} {name of author} - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - {project} Copyright (C) {year} {fullname} - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. diff --git a/lib/Arduino-INA226/README.md b/lib/Arduino-INA226/README.md deleted file mode 100644 index 43e2b756..00000000 --- a/lib/Arduino-INA226/README.md +++ /dev/null @@ -1,8 +0,0 @@ -Arduino-INA226 -============== - -INA226 Bi-directional Current/Power Monitor Arduino Library - -Tutorials: http://www.jarzebski.pl/arduino/czujniki-i-sensory/cyfrowy-czujnik-pradu-mocy-ina226.html - -This library use I2C to communicate, 2 pins are required to interface. diff --git a/lib/Arduino-IRremote/.gitignore b/lib/Arduino-IRremote/.gitignore deleted file mode 100644 index e24b84cd..00000000 --- a/lib/Arduino-IRremote/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -*.un~ -*.sublime-project -*.sublime-workspace \ No newline at end of file diff --git a/lib/Arduino-IRremote/.travis.yml b/lib/Arduino-IRremote/.travis.yml deleted file mode 100644 index 543a0a74..00000000 --- a/lib/Arduino-IRremote/.travis.yml +++ /dev/null @@ -1,30 +0,0 @@ -language: python -python: - - "2.7" - -# Cache PlatformIO packages using Travis CI container-based infrastructure -sudo: false -cache: - directories: - - "~/.platformio" - -env: - - PLATFORMIO_CI_SRC=examples/AiwaRCT501SendDemo PLATFORMIO_BUILD_FLAGS="-DSEND_AIWA_RC_T501" - - PLATFORMIO_CI_SRC=examples/IRrecord PLATFORMIO_BUILD_FLAGS="-DSEND_NEC -DSEND_SONY -DSEND_RC5 -DSEND_RC6" - - PLATFORMIO_CI_SRC=examples/IRrecvDemo - - PLATFORMIO_CI_SRC=examples/IRrecvDump - - PLATFORMIO_CI_SRC=examples/IRrecvDumpV2 - - PLATFORMIO_CI_SRC=examples/IRrelay - - PLATFORMIO_CI_SRC=examples/IRsendDemo PLATFORMIO_BUILD_FLAGS="-DSEND_SONY" - - PLATFORMIO_CI_SRC=examples/IRtest PLATFORMIO_BUILD_FLAGS="-DSEND_NEC -DSEND_SONY -DSEND_RC5 -DSEND_RC6" - - PLATFORMIO_CI_SRC=examples/IRtest2 PLATFORMIO_BUILD_FLAGS="-DSEND_NEC -DSEND_SONY -DSEND_RC5 -DSEND_RC6" - - PLATFORMIO_CI_SRC=examples/JVCPanasonicSendDemo PLATFORMIO_BUILD_FLAGS="-DSEND_JVC -DSEND_PANASONIC" - - PLATFORMIO_CI_SRC=examples/LegoPowerFunctionsSendDemo PLATFORMIO_BUILD_FLAGS="-DSEND_LEGO_PF" - - PLATFORMIO_CI_SRC=examples/LegoPowerFunctionsTests PLATFORMIO_BUILD_FLAGS="-DSEND_LEGO_PF" - - PLATFORMIO_CI_SRC=examples/IRremoteInfo - -install: - - pip install -U platformio - -script: - - platformio ci --lib="." --board=uno --board=leonardo --board=pro16MHzatmega168 --board=btatmega328 diff --git a/lib/Arduino-IRremote/Contributing.md b/lib/Arduino-IRremote/Contributing.md deleted file mode 100644 index 56409a9d..00000000 --- a/lib/Arduino-IRremote/Contributing.md +++ /dev/null @@ -1,11 +0,0 @@ -# Contribution Guidlines - -This library is the culmination of the expertise of many members of the open source community who have dedicated their time and hard work. The best way to ask for help or propose a new idea is to [create a new issue](https://github.com/z3t0/Arduino-IRremote/issues/new) while creating a Pull Request with your code changes allows you to share your own innovations with the rest of the community. - -The following are some guidelines to observe when creating issues or PRs: -- Be friendly; it is important that we can all enjoy a safe space as we are all working on the same project and it is okay for people to have different ideas -- [Use code blocks](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet#code); it helps us help you when we can read your code! On that note also refrain from pasting more than 30 lines of code in a post, instead [create a gist](https://gist.github.com/) if you need to share large snippets -- Use reasonable titles; refrain from using overly long or capitalized titles as they are usually annoying and do little to encourage others to help :smile: -- Be detailed; refrain from mentioning code problems without sharing your source code and always give information regarding your board and version of the library - -If there is any need to contact me then you can find my email on the README, I do not mind responding to emails but it would be in your own interests to create issues if you need help with the library as responses would be from a larger community with greater knowledge! \ No newline at end of file diff --git a/lib/Arduino-IRremote/Contributors.md b/lib/Arduino-IRremote/Contributors.md deleted file mode 100644 index 1bed7b6d..00000000 --- a/lib/Arduino-IRremote/Contributors.md +++ /dev/null @@ -1,22 +0,0 @@ -## Contributors -These are the active contributors of this project that you may contact if there is anything you need help with or if you have suggestions. - -- [z3t0](https://github.com/z3t0) : Active Contributor and currently also the main contributor. - * Email: zetoslab@gmail.com -- [shirriff](https://github.com/shirriff) : An amazing person who worked to create this awesome library and provide unending support -- [AnalysIR](https:/github.com/AnalysIR): Active contributor and is amazing with providing support! -- [Informatic](https://github.com/Informatic) : Active contributor -- [fmeschia](https://github.com/fmeschia) : Active contributor -- [PaulStoffregen](https://github.com/paulstroffregen) : Active contributor -- [crash7](https://github.com/crash7) : Active contributor -- [Neco777](https://github.com/neco777) : Active contributor -- [Lauszus](https://github.com/lauszus) : Active contributor -- [csBlueChip](https://github.com/csbluechip) : Active contributor, who contributed major and vital changes to the code base. -- [Sebazzz](https://github.com/sebazz): Contributor -- [lumbric](https://github.com/lumbric): Contributor -- [ElectricRCAircraftGuy](https://github.com/electricrcaircraftguy): Active Contributor -- [philipphenkel](https://github.com/philipphenkel): Active Contributor -- [MCUdude](https://github.com/MCUdude): Contributor -- [marcmerlin](https://github.com/marcmerlin): Contributor (ESP32 port) - -Note: This list is being updated constantly so please let [z3t0](https://github.com/z3t0) know if you have been missed. diff --git a/lib/Arduino-IRremote/IRremote.cpp b/lib/Arduino-IRremote/IRremote.cpp deleted file mode 100644 index e811cfc7..00000000 --- a/lib/Arduino-IRremote/IRremote.cpp +++ /dev/null @@ -1,200 +0,0 @@ -//****************************************************************************** -// IRremote -// Version 2.0.1 June, 2015 -// Copyright 2009 Ken Shirriff -// For details, see http://arcfn.com/2009/08/multi-protocol-infrared-remote-library.html -// -// Modified by Paul Stoffregen to support other boards and timers -// Modified by Mitra Ardron -// Added Sanyo and Mitsubishi controllers -// Modified Sony to spot the repeat codes that some Sony's send -// -// Interrupt code based on NECIRrcv by Joe Knapp -// http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1210243556 -// Also influenced by http://zovirl.com/2008/11/12/building-a-universal-remote-with-an-arduino/ -// -// JVC and Panasonic protocol added by Kristian Lauszus (Thanks to zenwheel and other people at the original blog post) -// LG added by Darryl Smith (based on the JVC protocol) -// Whynter A/C ARC-110WD added by Francesco Meschia -//****************************************************************************** - -// Defining IR_GLOBAL here allows us to declare the instantiation of global variables -#define IR_GLOBAL -# include "IRremote.h" -# include "IRremoteInt.h" -#undef IR_GLOBAL - -#ifndef IR_TIMER_USE_ESP32 -#include -#endif - - -//+============================================================================= -// The match functions were (apparently) originally MACROs to improve code speed -// (although this would have bloated the code) hence the names being CAPS -// A later release implemented debug output and so they needed to be converted -// to functions. -// I tried to implement a dual-compile mode (DEBUG/non-DEBUG) but for some -// reason, no matter what I did I could not get them to function as macros again. -// I have found a *lot* of bugs in the Arduino compiler over the last few weeks, -// and I am currently assuming that one of these bugs is my problem. -// I may revisit this code at a later date and look at the assembler produced -// in a hope of finding out what is going on, but for now they will remain as -// functions even in non-DEBUG mode -// -int MATCH (int measured, int desired) -{ - DBG_PRINT(F("Testing: ")); - DBG_PRINT(TICKS_LOW(desired), DEC); - DBG_PRINT(F(" <= ")); - DBG_PRINT(measured, DEC); - DBG_PRINT(F(" <= ")); - DBG_PRINT(TICKS_HIGH(desired), DEC); - - bool passed = ((measured >= TICKS_LOW(desired)) && (measured <= TICKS_HIGH(desired))); - if (passed) - DBG_PRINTLN(F("?; passed")); - else - DBG_PRINTLN(F("?; FAILED")); - return passed; -} - -//+======================================================== -// Due to sensor lag, when received, Marks tend to be 100us too long -// -int MATCH_MARK (int measured_ticks, int desired_us) -{ - DBG_PRINT(F("Testing mark (actual vs desired): ")); - DBG_PRINT(measured_ticks * USECPERTICK, DEC); - DBG_PRINT(F("us vs ")); - DBG_PRINT(desired_us, DEC); - DBG_PRINT("us"); - DBG_PRINT(": "); - DBG_PRINT(TICKS_LOW(desired_us + MARK_EXCESS) * USECPERTICK, DEC); - DBG_PRINT(F(" <= ")); - DBG_PRINT(measured_ticks * USECPERTICK, DEC); - DBG_PRINT(F(" <= ")); - DBG_PRINT(TICKS_HIGH(desired_us + MARK_EXCESS) * USECPERTICK, DEC); - - bool passed = ((measured_ticks >= TICKS_LOW (desired_us + MARK_EXCESS)) - && (measured_ticks <= TICKS_HIGH(desired_us + MARK_EXCESS))); - if (passed) - DBG_PRINTLN(F("?; passed")); - else - DBG_PRINTLN(F("?; FAILED")); - return passed; -} - -//+======================================================== -// Due to sensor lag, when received, Spaces tend to be 100us too short -// -int MATCH_SPACE (int measured_ticks, int desired_us) -{ - DBG_PRINT(F("Testing space (actual vs desired): ")); - DBG_PRINT(measured_ticks * USECPERTICK, DEC); - DBG_PRINT(F("us vs ")); - DBG_PRINT(desired_us, DEC); - DBG_PRINT("us"); - DBG_PRINT(": "); - DBG_PRINT(TICKS_LOW(desired_us - MARK_EXCESS) * USECPERTICK, DEC); - DBG_PRINT(F(" <= ")); - DBG_PRINT(measured_ticks * USECPERTICK, DEC); - DBG_PRINT(F(" <= ")); - DBG_PRINT(TICKS_HIGH(desired_us - MARK_EXCESS) * USECPERTICK, DEC); - - bool passed = ((measured_ticks >= TICKS_LOW (desired_us - MARK_EXCESS)) - && (measured_ticks <= TICKS_HIGH(desired_us - MARK_EXCESS))); - if (passed) - DBG_PRINTLN(F("?; passed")); - else - DBG_PRINTLN(F("?; FAILED")); - return passed; -} - -//+============================================================================= -// Interrupt Service Routine - Fires every 50uS -// TIMER2 interrupt code to collect raw data. -// Widths of alternating SPACE, MARK are recorded in rawbuf. -// Recorded in ticks of 50uS [microseconds, 0.000050 seconds] -// 'rawlen' counts the number of entries recorded so far. -// First entry is the SPACE between transmissions. -// As soon as a the first [SPACE] entry gets long: -// Ready is set; State switches to IDLE; Timing of SPACE continues. -// As soon as first MARK arrives: -// Gap width is recorded; Ready is cleared; New logging starts -// -#ifdef IR_TIMER_USE_ESP32 -void IRTimer() -#else -ISR (TIMER_INTR_NAME) -#endif -{ - TIMER_RESET; - - // Read if IR Receiver -> SPACE [xmt LED off] or a MARK [xmt LED on] - // digitalRead() is very slow. Optimisation is possible, but makes the code unportable - uint8_t irdata = (uint8_t)digitalRead(irparams.recvpin); - - irparams.timer++; // One more 50uS tick - if (irparams.rawlen >= RAWBUF) irparams.rcvstate = STATE_OVERFLOW ; // Buffer overflow - - switch(irparams.rcvstate) { - //...................................................................... - case STATE_IDLE: // In the middle of a gap - if (irdata == MARK) { - if (irparams.timer < GAP_TICKS) { // Not big enough to be a gap. - irparams.timer = 0; - - } else { - // Gap just ended; Record duration; Start recording transmission - irparams.overflow = false; - irparams.rawlen = 0; - irparams.rawbuf[irparams.rawlen++] = irparams.timer; - irparams.timer = 0; - irparams.rcvstate = STATE_MARK; - } - } - break; - //...................................................................... - case STATE_MARK: // Timing Mark - if (irdata == SPACE) { // Mark ended; Record time - irparams.rawbuf[irparams.rawlen++] = irparams.timer; - irparams.timer = 0; - irparams.rcvstate = STATE_SPACE; - } - break; - //...................................................................... - case STATE_SPACE: // Timing Space - if (irdata == MARK) { // Space just ended; Record time - irparams.rawbuf[irparams.rawlen++] = irparams.timer; - irparams.timer = 0; - irparams.rcvstate = STATE_MARK; - - } else if (irparams.timer > GAP_TICKS) { // Space - // A long Space, indicates gap between codes - // Flag the current code as ready for processing - // Switch to STOP - // Don't reset timer; keep counting Space width - irparams.rcvstate = STATE_STOP; - } - break; - //...................................................................... - case STATE_STOP: // Waiting; Measuring Gap - if (irdata == MARK) irparams.timer = 0 ; // Reset gap timer - break; - //...................................................................... - case STATE_OVERFLOW: // Flag up a read overflow; Stop the State Machine - irparams.overflow = true; - irparams.rcvstate = STATE_STOP; - break; - } - - // If requested, flash LED while receiving IR data - if (irparams.blinkflag) { - if (irdata == MARK) - if (irparams.blinkpin) digitalWrite(irparams.blinkpin, HIGH); // Turn user defined pin LED on - else BLINKLED_ON() ; // if no user defined LED pin, turn default LED pin for the hardware on - else if (irparams.blinkpin) digitalWrite(irparams.blinkpin, LOW); // Turn user defined pin LED on - else BLINKLED_OFF() ; // if no user defined LED pin, turn default LED pin for the hardware on - } -} diff --git a/lib/Arduino-IRremote/IRremote.h b/lib/Arduino-IRremote/IRremote.h deleted file mode 100644 index fe1a8702..00000000 --- a/lib/Arduino-IRremote/IRremote.h +++ /dev/null @@ -1,344 +0,0 @@ - -//****************************************************************************** -// IRremote -// Version 2.0.1 June, 2015 -// Copyright 2009 Ken Shirriff -// For details, see http://arcfn.com/2009/08/multi-protocol-infrared-remote-library.html -// Edited by Mitra to add new controller SANYO -// -// Interrupt code based on NECIRrcv by Joe Knapp -// http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1210243556 -// Also influenced by http://zovirl.com/2008/11/12/building-a-universal-remote-with-an-arduino/ -// -// JVC and Panasonic protocol added by Kristian Lauszus (Thanks to zenwheel and other people at the original blog post) -// LG added by Darryl Smith (based on the JVC protocol) -// Whynter A/C ARC-110WD added by Francesco Meschia -//****************************************************************************** - -#ifndef IRremote_h -#define IRremote_h - -//------------------------------------------------------------------------------ -// The ISR header contains several useful macros the user may wish to use -// -#include "IRremoteInt.h" - -//------------------------------------------------------------------------------ -// Supported IR protocols -// Each protocol you include costs memory and, during decode, costs time -// Disable (set to 0) all the protocols you do not need/want! -// -#define DECODE_RC5 1 -#define SEND_RC5 1 - -#define DECODE_RC6 1 -#define SEND_RC6 1 - -#define DECODE_NEC 1 -#define SEND_NEC 1 - -#define DECODE_SONY 1 -#define SEND_SONY 1 - -#define DECODE_PANASONIC 1 -#define SEND_PANASONIC 1 - -#define DECODE_JVC 1 -#define SEND_JVC 1 - -#define DECODE_SAMSUNG 1 -#define SEND_SAMSUNG 1 - -#define DECODE_WHYNTER 1 -#define SEND_WHYNTER 1 - -#define DECODE_AIWA_RC_T501 1 -#define SEND_AIWA_RC_T501 1 - -#define DECODE_LG 1 -#define SEND_LG 1 - -#define DECODE_SANYO 1 -#define SEND_SANYO 0 // NOT WRITTEN - -#define DECODE_MITSUBISHI 1 -#define SEND_MITSUBISHI 0 // NOT WRITTEN - -#define DECODE_DISH 0 // NOT WRITTEN -#define SEND_DISH 1 - -#define DECODE_SHARP 0 // NOT WRITTEN -#define SEND_SHARP 1 - -#define DECODE_DENON 1 -#define SEND_DENON 1 - -#define DECODE_PRONTO 0 // This function doe not logically make sense -#define SEND_PRONTO 1 - -#define DECODE_LEGO_PF 0 // NOT WRITTEN -#define SEND_LEGO_PF 1 - -//------------------------------------------------------------------------------ -// When sending a Pronto code we request to send either the "once" code -// or the "repeat" code -// If the code requested does not exist we can request to fallback on the -// other code (the one we did not explicitly request) -// -// I would suggest that "fallback" will be the standard calling method -// The last paragraph on this page discusses the rationale of this idea: -// http://www.remotecentral.com/features/irdisp2.htm -// -#define PRONTO_ONCE false -#define PRONTO_REPEAT true -#define PRONTO_FALLBACK true -#define PRONTO_NOFALLBACK false - -//------------------------------------------------------------------------------ -// An enumerated list of all supported formats -// You do NOT need to remove entries from this list when disabling protocols! -// -typedef - enum { - UNKNOWN = -1, - UNUSED = 0, - RC5, - RC6, - NEC, - SONY, - PANASONIC, - JVC, - SAMSUNG, - WHYNTER, - AIWA_RC_T501, - LG, - SANYO, - MITSUBISHI, - DISH, - SHARP, - DENON, - PRONTO, - LEGO_PF, - } -decode_type_t; - -//------------------------------------------------------------------------------ -// Set DEBUG to 1 for lots of lovely debug output -// -#define DEBUG 0 - -//------------------------------------------------------------------------------ -// Debug directives -// -#if DEBUG -# define DBG_PRINT(...) Serial.print(__VA_ARGS__) -# define DBG_PRINTLN(...) Serial.println(__VA_ARGS__) -#else -# define DBG_PRINT(...) -# define DBG_PRINTLN(...) -#endif - -//------------------------------------------------------------------------------ -// Mark & Space matching functions -// -int MATCH (int measured, int desired) ; -int MATCH_MARK (int measured_ticks, int desired_us) ; -int MATCH_SPACE (int measured_ticks, int desired_us) ; - -//------------------------------------------------------------------------------ -// Results returned from the decoder -// -class decode_results -{ - public: - decode_type_t decode_type; // UNKNOWN, NEC, SONY, RC5, ... - unsigned int address; // Used by Panasonic & Sharp [16-bits] - unsigned long value; // Decoded value [max 32-bits] - int bits; // Number of bits in decoded value - volatile unsigned int *rawbuf; // Raw intervals in 50uS ticks - int rawlen; // Number of records in rawbuf - int overflow; // true iff IR raw code too long -}; - -//------------------------------------------------------------------------------ -// Decoded value for NEC when a repeat code is received -// -#define REPEAT 0xFFFFFFFF - -//------------------------------------------------------------------------------ -// Main class for receiving IR -// -class IRrecv -{ - public: - IRrecv (int recvpin) ; - IRrecv (int recvpin, int blinkpin); - - void blink13 (int blinkflag) ; - int decode (decode_results *results) ; - void enableIRIn ( ) ; - bool isIdle ( ) ; - void resume ( ) ; - - private: - long decodeHash (decode_results *results) ; - int compare (unsigned int oldval, unsigned int newval) ; - - //...................................................................... -# if (DECODE_RC5 || DECODE_RC6) - // This helper function is shared by RC5 and RC6 - int getRClevel (decode_results *results, int *offset, int *used, int t1) ; -# endif -# if DECODE_RC5 - bool decodeRC5 (decode_results *results) ; -# endif -# if DECODE_RC6 - bool decodeRC6 (decode_results *results) ; -# endif - //...................................................................... -# if DECODE_NEC - bool decodeNEC (decode_results *results) ; -# endif - //...................................................................... -# if DECODE_SONY - bool decodeSony (decode_results *results) ; -# endif - //...................................................................... -# if DECODE_PANASONIC - bool decodePanasonic (decode_results *results) ; -# endif - //...................................................................... -# if DECODE_JVC - bool decodeJVC (decode_results *results) ; -# endif - //...................................................................... -# if DECODE_SAMSUNG - bool decodeSAMSUNG (decode_results *results) ; -# endif - //...................................................................... -# if DECODE_WHYNTER - bool decodeWhynter (decode_results *results) ; -# endif - //...................................................................... -# if DECODE_AIWA_RC_T501 - bool decodeAiwaRCT501 (decode_results *results) ; -# endif - //...................................................................... -# if DECODE_LG - bool decodeLG (decode_results *results) ; -# endif - //...................................................................... -# if DECODE_SANYO - bool decodeSanyo (decode_results *results) ; -# endif - //...................................................................... -# if DECODE_MITSUBISHI - bool decodeMitsubishi (decode_results *results) ; -# endif - //...................................................................... -# if DECODE_DISH - bool decodeDish (decode_results *results) ; // NOT WRITTEN -# endif - //...................................................................... -# if DECODE_SHARP - bool decodeSharp (decode_results *results) ; // NOT WRITTEN -# endif - //...................................................................... -# if DECODE_DENON - bool decodeDenon (decode_results *results) ; -# endif -//...................................................................... -# if DECODE_LEGO_PF - bool decodeLegoPowerFunctions (decode_results *results) ; -# endif -} ; - -//------------------------------------------------------------------------------ -// Main class for sending IR -// -class IRsend -{ - public: - IRsend () { } - - void custom_delay_usec (unsigned long uSecs); - void enableIROut (int khz) ; - void mark (unsigned int usec) ; - void space (unsigned int usec) ; - void sendRaw (const unsigned int buf[], unsigned int len, unsigned int hz) ; - - //...................................................................... -# if SEND_RC5 - void sendRC5 (unsigned long data, int nbits) ; -# endif -# if SEND_RC6 - void sendRC6 (unsigned long data, int nbits) ; -# endif - //...................................................................... -# if SEND_NEC - void sendNEC (unsigned long data, int nbits) ; -# endif - //...................................................................... -# if SEND_SONY - void sendSony (unsigned long data, int nbits) ; -# endif - //...................................................................... -# if SEND_PANASONIC - void sendPanasonic (unsigned int address, unsigned long data) ; -# endif - //...................................................................... -# if SEND_JVC - // JVC does NOT repeat by sending a separate code (like NEC does). - // The JVC protocol repeats by skipping the header. - // To send a JVC repeat signal, send the original code value - // and set 'repeat' to true - void sendJVC (unsigned long data, int nbits, bool repeat) ; -# endif - //...................................................................... -# if SEND_SAMSUNG - void sendSAMSUNG (unsigned long data, int nbits) ; -# endif - //...................................................................... -# if SEND_WHYNTER - void sendWhynter (unsigned long data, int nbits) ; -# endif - //...................................................................... -# if SEND_AIWA_RC_T501 - void sendAiwaRCT501 (int code) ; -# endif - //...................................................................... -# if SEND_LG - void sendLG (unsigned long data, int nbits) ; -# endif - //...................................................................... -# if SEND_SANYO - void sendSanyo ( ) ; // NOT WRITTEN -# endif - //...................................................................... -# if SEND_MISUBISHI - void sendMitsubishi ( ) ; // NOT WRITTEN -# endif - //...................................................................... -# if SEND_DISH - void sendDISH (unsigned long data, int nbits) ; -# endif - //...................................................................... -# if SEND_SHARP - void sendSharpRaw (unsigned long data, int nbits) ; - void sendSharp (unsigned int address, unsigned int command) ; -# endif - //...................................................................... -# if SEND_DENON - void sendDenon (unsigned long data, int nbits) ; -# endif - //...................................................................... -# if SEND_PRONTO - void sendPronto (char* code, bool repeat, bool fallback) ; -# endif -//...................................................................... -# if SEND_LEGO_PF - void sendLegoPowerFunctions (uint16_t data, bool repeat = true) ; -# endif -} ; - -#endif diff --git a/lib/Arduino-IRremote/IRremoteInt.h b/lib/Arduino-IRremote/IRremoteInt.h deleted file mode 100644 index 1c319acb..00000000 --- a/lib/Arduino-IRremote/IRremoteInt.h +++ /dev/null @@ -1,113 +0,0 @@ -//****************************************************************************** -// IRremote -// Version 2.0.1 June, 2015 -// Copyright 2009 Ken Shirriff -// For details, see http://arcfn.com/2009/08/multi-protocol-infrared-remote-library.html -// -// Modified by Paul Stoffregen to support other boards and timers -// -// Interrupt code based on NECIRrcv by Joe Knapp -// http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1210243556 -// Also influenced by http://zovirl.com/2008/11/12/building-a-universal-remote-with-an-arduino/ -// -// JVC and Panasonic protocol added by Kristian Lauszus (Thanks to zenwheel and other people at the original blog post) -// Whynter A/C ARC-110WD added by Francesco Meschia -//****************************************************************************** - -#ifndef IRremoteint_h -#define IRremoteint_h - -//------------------------------------------------------------------------------ -// Include the right Arduino header -// -#if defined(ARDUINO) && (ARDUINO >= 100) -# include -#else -# if !defined(IRPRONTO) -# include -# endif -#endif - -//------------------------------------------------------------------------------ -// This handles definition and access to global variables -// -#ifdef IR_GLOBAL -# define EXTERN -#else -# define EXTERN extern -#endif - -//------------------------------------------------------------------------------ -// Information for the Interrupt Service Routine -// -#define RAWBUF 101 // Maximum length of raw duration buffer - -typedef - struct { - // The fields are ordered to reduce memory over caused by struct-padding - uint8_t rcvstate; // State Machine state - uint8_t recvpin; // Pin connected to IR data from detector - uint8_t blinkpin; - uint8_t blinkflag; // true -> enable blinking of pin on IR processing - uint8_t rawlen; // counter of entries in rawbuf - unsigned int timer; // State timer, counts 50uS ticks. - unsigned int rawbuf[RAWBUF]; // raw data - uint8_t overflow; // Raw buffer overflow occurred - } -irparams_t; - -// ISR State-Machine : Receiver States -#define STATE_IDLE 2 -#define STATE_MARK 3 -#define STATE_SPACE 4 -#define STATE_STOP 5 -#define STATE_OVERFLOW 6 - -// Allow all parts of the code access to the ISR data -// NB. The data can be changed by the ISR at any time, even mid-function -// Therefore we declare it as "volatile" to stop the compiler/CPU caching it -EXTERN volatile irparams_t irparams; - -//------------------------------------------------------------------------------ -// Defines for setting and clearing register bits -// -#ifndef cbi -# define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit)) -#endif - -#ifndef sbi -# define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit)) -#endif - -//------------------------------------------------------------------------------ -// Pulse parms are ((X*50)-100) for the Mark and ((X*50)+100) for the Space. -// First MARK is the one after the long gap -// Pulse parameters in uSec -// - -// Due to sensor lag, when received, Marks tend to be 100us too long and -// Spaces tend to be 100us too short -#define MARK_EXCESS 100 - -// Upper and Lower percentage tolerances in measurements -#define TOLERANCE 25 -#define LTOL (1.0 - (TOLERANCE/100.)) -#define UTOL (1.0 + (TOLERANCE/100.)) - -// Minimum gap between IR transmissions -#define _GAP 5000 -#define GAP_TICKS (_GAP/USECPERTICK) - -#define TICKS_LOW(us) ((int)(((us)*LTOL/USECPERTICK))) -#define TICKS_HIGH(us) ((int)(((us)*UTOL/USECPERTICK + 1))) - -//------------------------------------------------------------------------------ -// IR detector output is active low -// -#define MARK 0 -#define SPACE 1 - -// All board specific stuff has been moved to its own file, included here. -#include "boarddefs.h" - -#endif diff --git a/lib/Arduino-IRremote/ISSUE_TEMPLATE.md b/lib/Arduino-IRremote/ISSUE_TEMPLATE.md deleted file mode 100644 index 98358d0e..00000000 --- a/lib/Arduino-IRremote/ISSUE_TEMPLATE.md +++ /dev/null @@ -1,25 +0,0 @@ -**Board:** ARDUINO UNO -**Library Version:** 2.1.0 -**Protocol:** Sony (if any) - -**Code Block:** -```c - -#include - -..... - -``` - -Use [a gist](gist.github.com) if the code exceeds 30 lines - -**checklist:** -- [] I have **read** the README.md file thoroughly -- [] I have searched existing issues to see if there is anything I have missed. -- [] The latest [release](https://github.com/z3t0/Arduino-IRremote/releases/latest) is used -- [] Any code referenced is provided and if over 30 lines a gist is linked INSTEAD of it being pasted in here -- [] The title of the issue is helpful and relevant - -** We will start to close issues that do not follow these guidelines as it doesn't help the contributors who spend time trying to solve issues if the community ignores guidelines!** - -The above is a short template allowing you to make detailed issues! diff --git a/lib/Arduino-IRremote/LICENSE.txt b/lib/Arduino-IRremote/LICENSE.txt deleted file mode 100644 index 77cec6dd..00000000 --- a/lib/Arduino-IRremote/LICENSE.txt +++ /dev/null @@ -1,458 +0,0 @@ - - GNU LESSER GENERAL PUBLIC LICENSE - Version 2.1, February 1999 - - Copyright (C) 1991, 1999 Free Software Foundation, Inc. - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - -[This is the first released version of the Lesser GPL. It also counts - as the successor of the GNU Library Public License, version 2, hence - the version number 2.1.] - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -Licenses are intended to guarantee your freedom to share and change -free software--to make sure the software is free for all its users. - - This license, the Lesser General Public License, applies to some -specially designated software packages--typically libraries--of the -Free Software Foundation and other authors who decide to use it. You -can use it too, but we suggest you first think carefully about whether -this license or the ordinary General Public License is the better -strategy to use in any particular case, based on the explanations below. - - When we speak of free software, we are referring to freedom of use, -not price. Our General Public Licenses are designed to make sure that -you have the freedom to distribute copies of free software (and charge -for this service if you wish); that you receive source code or can get -it if you want it; that you can change the software and use pieces of -it in new free programs; and that you are informed that you can do -these things. - - To protect your rights, we need to make restrictions that forbid -distributors to deny you these rights or to ask you to surrender these -rights. These restrictions translate to certain responsibilities for -you if you distribute copies of the library or if you modify it. - - For example, if you distribute copies of the library, whether gratis -or for a fee, you must give the recipients all the rights that we gave -you. You must make sure that they, too, receive or can get the source -code. If you link other code with the library, you must provide -complete object files to the recipients, so that they can relink them -with the library after making changes to the library and recompiling -it. And you must show them these terms so they know their rights. - - We protect your rights with a two-step method: (1) we copyright the -library, and (2) we offer you this license, which gives you legal -permission to copy, distribute and/or modify the library. - - To protect each distributor, we want to make it very clear that -there is no warranty for the free library. Also, if the library is -modified by someone else and passed on, the recipients should know -that what they have is not the original version, so that the original -author's reputation will not be affected by problems that might be -introduced by others. - - Finally, software patents pose a constant threat to the existence of -any free program. We wish to make sure that a company cannot -effectively restrict the users of a free program by obtaining a -restrictive license from a patent holder. Therefore, we insist that -any patent license obtained for a version of the library must be -consistent with the full freedom of use specified in this license. - - Most GNU software, including some libraries, is covered by the -ordinary GNU General Public License. This license, the GNU Lesser -General Public License, applies to certain designated libraries, and -is quite different from the ordinary General Public License. We use -this license for certain libraries in order to permit linking those -libraries into non-free programs. - - When a program is linked with a library, whether statically or using -a shared library, the combination of the two is legally speaking a -combined work, a derivative of the original library. The ordinary -General Public License therefore permits such linking only if the -entire combination fits its criteria of freedom. The Lesser General -Public License permits more lax criteria for linking other code with -the library. - - We call this license the "Lesser" General Public License because it -does Less to protect the user's freedom than the ordinary General -Public License. It also provides other free software developers Less -of an advantage over competing non-free programs. These disadvantages -are the reason we use the ordinary General Public License for many -libraries. However, the Lesser license provides advantages in certain -special circumstances. - - For example, on rare occasions, there may be a special need to -encourage the widest possible use of a certain library, so that it becomes -a de-facto standard. To achieve this, non-free programs must be -allowed to use the library. A more frequent case is that a free -library does the same job as widely used non-free libraries. In this -case, there is little to gain by limiting the free library to free -software only, so we use the Lesser General Public License. - - In other cases, permission to use a particular library in non-free -programs enables a greater number of people to use a large body of -free software. For example, permission to use the GNU C Library in -non-free programs enables many more people to use the whole GNU -operating system, as well as its variant, the GNU/Linux operating -system. - - Although the Lesser General Public License is Less protective of the -users' freedom, it does ensure that the user of a program that is -linked with the Library has the freedom and the wherewithal to run -that program using a modified version of the Library. - - The precise terms and conditions for copying, distribution and -modification follow. Pay close attention to the difference between a -"work based on the library" and a "work that uses the library". The -former contains code derived from the library, whereas the latter must -be combined with the library in order to run. - - GNU LESSER GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License Agreement applies to any software library or other -program which contains a notice placed by the copyright holder or -other authorized party saying it may be distributed under the terms of -this Lesser General Public License (also called "this License"). -Each licensee is addressed as "you". - - A "library" means a collection of software functions and/or data -prepared so as to be conveniently linked with application programs -(which use some of those functions and data) to form executables. - - The "Library", below, refers to any such software library or work -which has been distributed under these terms. A "work based on the -Library" means either the Library or any derivative work under -copyright law: that is to say, a work containing the Library or a -portion of it, either verbatim or with modifications and/or translated -straightforwardly into another language. (Hereinafter, translation is -included without limitation in the term "modification".) - - "Source code" for a work means the preferred form of the work for -making modifications to it. For a library, complete source code means -all the source code for all modules it contains, plus any associated -interface definition files, plus the scripts used to control compilation -and installation of the library. - - Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running a program using the Library is not restricted, and output from -such a program is covered only if its contents constitute a work based -on the Library (independent of the use of the Library in a tool for -writing it). Whether that is true depends on what the Library does -and what the program that uses the Library does. - - 1. You may copy and distribute verbatim copies of the Library's -complete source code as you receive it, in any medium, provided that -you conspicuously and appropriately publish on each copy an -appropriate copyright notice and disclaimer of warranty; keep intact -all the notices that refer to this License and to the absence of any -warranty; and distribute a copy of this License along with the -Library. - - You may charge a fee for the physical act of transferring a copy, -and you may at your option offer warranty protection in exchange for a -fee. - - 2. You may modify your copy or copies of the Library or any portion -of it, thus forming a work based on the Library, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) The modified work must itself be a software library. - - b) You must cause the files modified to carry prominent notices - stating that you changed the files and the date of any change. - - c) You must cause the whole of the work to be licensed at no - charge to all third parties under the terms of this License. - - d) If a facility in the modified Library refers to a function or a - table of data to be supplied by an application program that uses - the facility, other than as an argument passed when the facility - is invoked, then you must make a good faith effort to ensure that, - in the event an application does not supply such function or - table, the facility still operates, and performs whatever part of - its purpose remains meaningful. - - (For example, a function in a library to compute square roots has - a purpose that is entirely well-defined independent of the - application. Therefore, Subsection 2d requires that any - application-supplied function or table used by this function must - be optional: if the application does not supply it, the square - root function must still compute square roots.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Library, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Library, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote -it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Library. - -In addition, mere aggregation of another work not based on the Library -with the Library (or with a work based on the Library) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may opt to apply the terms of the ordinary GNU General Public -License instead of this License to a given copy of the Library. To do -this, you must alter all the notices that refer to this License, so -that they refer to the ordinary GNU General Public License, version 2, -instead of to this License. (If a newer version than version 2 of the -ordinary GNU General Public License has appeared, then you can specify -that version instead if you wish.) Do not make any other change in -these notices. - - Once this change is made in a given copy, it is irreversible for -that copy, so the ordinary GNU General Public License applies to all -subsequent copies and derivative works made from that copy. - - This option is useful when you wish to copy part of the code of -the Library into a program that is not a library. - - 4. You may copy and distribute the Library (or a portion or -derivative of it, under Section 2) in object code or executable form -under the terms of Sections 1 and 2 above provided that you accompany -it with the complete corresponding machine-readable source code, which -must be distributed under the terms of Sections 1 and 2 above on a -medium customarily used for software interchange. - - If distribution of object code is made by offering access to copy -from a designated place, then offering equivalent access to copy the -source code from the same place satisfies the requirement to -distribute the source code, even though third parties are not -compelled to copy the source along with the object code. - - 5. A program that contains no derivative of any portion of the -Library, but is designed to work with the Library by being compiled or -linked with it, is called a "work that uses the Library". Such a -work, in isolation, is not a derivative work of the Library, and -therefore falls outside the scope of this License. - - However, linking a "work that uses the Library" with the Library -creates an executable that is a derivative of the Library (because it -contains portions of the Library), rather than a "work that uses the -library". The executable is therefore covered by this License. -Section 6 states terms for distribution of such executables. - - When a "work that uses the Library" uses material from a header file -that is part of the Library, the object code for the work may be a -derivative work of the Library even though the source code is not. -Whether this is true is especially significant if the work can be -linked without the Library, or if the work is itself a library. The -threshold for this to be true is not precisely defined by law. - - If such an object file uses only numerical parameters, data -structure layouts and accessors, and small macros and small inline -functions (ten lines or less in length), then the use of the object -file is unrestricted, regardless of whether it is legally a derivative -work. (Executables containing this object code plus portions of the -Library will still fall under Section 6.) - - Otherwise, if the work is a derivative of the Library, you may -distribute the object code for the work under the terms of Section 6. -Any executables containing that work also fall under Section 6, -whether or not they are linked directly with the Library itself. - - 6. As an exception to the Sections above, you may also combine or -link a "work that uses the Library" with the Library to produce a -work containing portions of the Library, and distribute that work -under terms of your choice, provided that the terms permit -modification of the work for the customer's own use and reverse -engineering for debugging such modifications. - - You must give prominent notice with each copy of the work that the -Library is used in it and that the Library and its use are covered by -this License. You must supply a copy of this License. If the work -during execution displays copyright notices, you must include the -copyright notice for the Library among them, as well as a reference -directing the user to the copy of this License. Also, you must do one -of these things: - - a) Accompany the work with the complete corresponding - machine-readable source code for the Library including whatever - changes were used in the work (which must be distributed under - Sections 1 and 2 above); and, if the work is an executable linked - with the Library, with the complete machine-readable "work that - uses the Library", as object code and/or source code, so that the - user can modify the Library and then relink to produce a modified - executable containing the modified Library. (It is understood - that the user who changes the contents of definitions files in the - Library will not necessarily be able to recompile the application - to use the modified definitions.) - - b) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (1) uses at run time a - copy of the library already present on the user's computer system, - rather than copying library functions into the executable, and (2) - will operate properly with a modified version of the library, if - the user installs one, as long as the modified version is - interface-compatible with the version that the work was made with. - - c) Accompany the work with a written offer, valid for at - least three years, to give the same user the materials - specified in Subsection 6a, above, for a charge no more - than the cost of performing this distribution. - - d) If distribution of the work is made by offering access to copy - from a designated place, offer equivalent access to copy the above - specified materials from the same place. - - e) Verify that the user has already received a copy of these - materials or that you have already sent this user a copy. - - For an executable, the required form of the "work that uses the -Library" must include any data and utility programs needed for -reproducing the executable from it. However, as a special exception, -the materials to be distributed need not include anything that is -normally distributed (in either source or binary form) with the major -components (compiler, kernel, and so on) of the operating system on -which the executable runs, unless that component itself accompanies -the executable. - - It may happen that this requirement contradicts the license -restrictions of other proprietary libraries that do not normally -accompany the operating system. Such a contradiction means you cannot -use both them and the Library together in an executable that you -distribute. - - 7. You may place library facilities that are a work based on the -Library side-by-side in a single library together with other library -facilities not covered by this License, and distribute such a combined -library, provided that the separate distribution of the work based on -the Library and of the other library facilities is otherwise -permitted, and provided that you do these two things: - - a) Accompany the combined library with a copy of the same work - based on the Library, uncombined with any other library - facilities. This must be distributed under the terms of the - Sections above. - - b) Give prominent notice with the combined library of the fact - that part of it is a work based on the Library, and explaining - where to find the accompanying uncombined form of the same work. - - 8. You may not copy, modify, sublicense, link with, or distribute -the Library except as expressly provided under this License. Any -attempt otherwise to copy, modify, sublicense, link with, or -distribute the Library is void, and will automatically terminate your -rights under this License. However, parties who have received copies, -or rights, from you under this License will not have their licenses -terminated so long as such parties remain in full compliance. - - 9. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Library or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Library (or any work based on the -Library), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Library or works based on it. - - 10. Each time you redistribute the Library (or any work based on the -Library), the recipient automatically receives a license from the -original licensor to copy, distribute, link with or modify the Library -subject to these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties with -this License. - - 11. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Library at all. For example, if a patent -license would not permit royalty-free redistribution of the Library by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Library. - -If any portion of this section is held invalid or unenforceable under any -particular circumstance, the balance of the section is intended to apply, -and the section as a whole is intended to apply in other circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 12. If the distribution and/or use of the Library is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Library under this License may add -an explicit geographical distribution limitation excluding those countries, -so that distribution is permitted only in or among countries not thus -excluded. In such case, this License incorporates the limitation as if -written in the body of this License. - - 13. The Free Software Foundation may publish revised and/or new -versions of the Lesser General Public License from time to time. -Such new versions will be similar in spirit to the present version, -but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Library -specifies a version number of this License which applies to it and -"any later version", you have the option of following the terms and -conditions either of that version or of any later version published by -the Free Software Foundation. If the Library does not specify a -license version number, you may choose any version ever published by -the Free Software Foundation. - - 14. If you wish to incorporate parts of the Library into other free -programs whose distribution conditions are incompatible with these, -write to the author to ask for permission. For software which is -copyrighted by the Free Software Foundation, write to the Free -Software Foundation; we sometimes make exceptions for this. Our -decision will be guided by the two goals of preserving the free status -of all derivatives of our free software and of promoting the sharing -and reuse of software generally. - - NO WARRANTY - - 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO -WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. -EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR -OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY -KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE -LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME -THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN -WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY -AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU -FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR -CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE -LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING -RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A -FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF -SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH -DAMAGES. - diff --git a/lib/Arduino-IRremote/README.md b/lib/Arduino-IRremote/README.md deleted file mode 100644 index 00a4b03b..00000000 --- a/lib/Arduino-IRremote/README.md +++ /dev/null @@ -1,89 +0,0 @@ -# IRremote Arduino Library - -[![Build Status](https://travis-ci.org/z3t0/Arduino-IRremote.svg?branch=master)](https://travis-ci.org/z3t0/Arduino-IRremote) - -[![Join the chat at https://gitter.im/z3t0/Arduino-IRremote](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/z3t0/Arduino-IRremote?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) - -This library enables you to send and receive using infra-red signals on an Arduino. - -Tutorials and more information will be made available on [the official homepage](http://z3t0.github.io/Arduino-IRremote/). - -## Version - 2.2.3 - -## Installation -1. Navigate to the [Releases](https://github.com/z3t0/Arduino-IRremote/releases) page. -2. Download the latest release. -3. Extract the zip file -4. Move the "IRremote" folder that has been extracted to your libraries directory. -5. Make sure to delete Arduino_Root/libraries/RobotIRremote. Where Arduino_Root refers to the install directory of Arduino. The library RobotIRremote has similar definitions to IRremote and causes errors. - - -## FAQ -- IR does not work right when I use Neopixels (aka WS2811/WS2812/WS2812B) -Whether you use the Adafruit Neopixel lib, or FastLED, interrupts get disabled on many lower end CPUs like the basic arduinos. In turn, this stops the IR interrupt handler from running when it needs to. There are some solutions to this on some processors, [see this page from Marc MERLIN](http://marc.merlins.org/perso/arduino/post_2017-04-03_Arduino-328P-Uno-Teensy3_1-ESP8266-ESP32-IR-and-Neopixels.html) - - -## Supported Boards -- Arduino Uno / Mega / Leonardo / Duemilanove / Diecimila / LilyPad / Mini / Fio / Nano etc. -- Teensy 1.0 / 1.0++ / 2.0 / 2++ / 3.0 / 3.1 / Teensy-LC; Credits: @PaulStoffregen (Teensy Team) -- Sanguino -- ATmega8, 48, 88, 168, 328 -- ATmega8535, 16, 32, 164, 324, 644, 1284, -- ATmega64, 128 -- ATtiny 84 / 85 -- ESP32 (receive only) -- ESP8266 is supported in a fork based on an old codebase that isn't as recent, but it works reasonably well given that perfectly timed sub millisecond interrupts are different on that chip. See https://github.com/markszabo/IRremoteESP8266 - -We are open to suggestions for adding support to new boards, however we highly recommend you contact your supplier first and ask them to provide support from their side. - -### Hardware specifications - -| Board/CPU | Send Pin | Timers | -|--------------------------------------------------------------------------|---------------------|-------------------| -| [ATtiny84](https://github.com/SpenceKonde/ATTinyCore) | **6** | **1** | -| [ATtiny85](https://github.com/SpenceKonde/ATTinyCore) | **1** | **TINY0** | -| [ATmega8](https://github.com/MCUdude/MiniCore) | **9** | **1** | -| Atmega32u4 | 5, 9, **13** | 1, 3, **4** | -| [ATmega48, ATmega88, ATmega168, ATmega328](https://github.com/MCUdude/MiniCore) | **3**, 9 | 1, **2** | -| [ATmega1284](https://github.com/MCUdude/MightyCore) | 13, 14, 6 | 1, **2**, 3 | -| [ATmega164, ATmega324, ATmega644](https://github.com/MCUdude/MightyCore) | 13, **14** | 1, **2** | -| [ATmega8535 ATmega16, ATmega32](https://github.com/MCUdude/MightyCore) | **13** | **1** | -| [ATmega64, ATmega128](https://github.com/MCUdude/MegaCore) | **13** | **1** | -| ATmega1280, ATmega2560 | 5, 6, **9**, 11, 46 | 1, **2**, 3, 4, 5 | -| [ESP32](http://esp32.net/) | N/A (not supported) | **1** | -| [Teensy 1.0](https://www.pjrc.com/teensy/) | **17** | **1** | -| [Teensy 2.0](https://www.pjrc.com/teensy/) | 9, **10**, 14 | 1, 3, **4_HS** | -| [Teensy++ 1.0 / 2.0](https://www.pjrc.com/teensy/) | **1**, 16, 25 | 1, **2**, 3 | -| [Teensy 3.0 / 3.1](https://www.pjrc.com/teensy/) | **5** | **CMT** | -| [Teensy-LC](https://www.pjrc.com/teensy/) | **16** | **TPM1** | - - -### Experimental patches -The following are strictly community supported patches that have yet to make it into mainstream. If you have issues feel free to ask here. If it works well then let us know! - -[Arduino 101](https://github.com/z3t0/Arduino-IRremote/pull/481#issuecomment-311243146) - -The table above lists the currently supported timers and corresponding send pins, many of these can have additional pins opened up and we are open to requests if a need arises for other pins. - -## Usage -- TODO (Check examples for now) - -## Contributing -If you want to contribute to this project: -- Report bugs and errors -- Ask for enhancements -- Create issues and pull requests -- Tell other people about this library -- Contribute new protocols - -Check [here](Contributing.md) for some guidelines. - -## Contact -Email: zetoslab@gmail.com -Please only email me if it is more appropriate than creating an Issue / PR. I **will** not respond to requests for adding support for particular boards, unless of course you are the creator of the board and would like to cooperate on the project. I will also **ignore** any emails asking me to tell you how to implement your ideas. However, if you have a private inquiry that you would only apply to you and you would prefer it to be via email, by all means. - -## Contributors -Check [here](Contributors.md) - -## Copyright -Copyright 2009-2012 Ken Shirriff diff --git a/lib/Arduino-IRremote/boarddefs.h b/lib/Arduino-IRremote/boarddefs.h deleted file mode 100644 index 17e25513..00000000 --- a/lib/Arduino-IRremote/boarddefs.h +++ /dev/null @@ -1,577 +0,0 @@ -//****************************************************************************** -// IRremote -// Version 2.0.1 June, 2015 -// Copyright 2009 Ken Shirriff -// For details, see http://arcfn.com/2009/08/multi-protocol-infrared-remote-library.html - -// This file contains all board specific information. It was previously contained within -// IRremoteInt.h - -// Modified by Paul Stoffregen to support other boards and timers -// -// Interrupt code based on NECIRrcv by Joe Knapp -// http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1210243556 -// Also influenced by http://zovirl.com/2008/11/12/building-a-universal-remote-with-an-arduino/ -// -// JVC and Panasonic protocol added by Kristian Lauszus (Thanks to zenwheel and other people at the original blog post) -// Whynter A/C ARC-110WD added by Francesco Meschia -//****************************************************************************** - -#ifndef boarddefs_h -#define boarddefs_h - -//------------------------------------------------------------------------------ -// Defines for blinking the LED -// - -#if defined(CORE_LED0_PIN) -# define BLINKLED CORE_LED0_PIN -# define BLINKLED_ON() (digitalWrite(CORE_LED0_PIN, HIGH)) -# define BLINKLED_OFF() (digitalWrite(CORE_LED0_PIN, LOW)) - -#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) -# define BLINKLED 13 -# define BLINKLED_ON() (PORTB |= B10000000) -# define BLINKLED_OFF() (PORTB &= B01111111) - -#elif defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644__) -# define BLINKLED 0 -# define BLINKLED_ON() (PORTD |= B00000001) -# define BLINKLED_OFF() (PORTD &= B11111110) - -// No system LED on ESP32, disable blinking -#elif defined(ESP32) -# define BLINKLED 255 -# define BLINKLED_ON() 1 -# define BLINKLED_OFF() 1 -#else -# define BLINKLED 13 -# define BLINKLED_ON() (PORTB |= B00100000) -# define BLINKLED_OFF() (PORTB &= B11011111) -#endif - -//------------------------------------------------------------------------------ -// CPU Frequency -// -#ifdef F_CPU -# define SYSCLOCK F_CPU // main Arduino clock -#else -# define SYSCLOCK 16000000 // main Arduino clock -#endif - -// microseconds per clock interrupt tick -#define USECPERTICK 50 - -//------------------------------------------------------------------------------ -// Define which timer to use -// -// Uncomment the timer you wish to use on your board. -// If you are using another library which uses timer2, you have options to -// switch IRremote to use a different timer. -// - -// Arduino Mega -#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) - //#define IR_USE_TIMER1 // tx = pin 11 - #define IR_USE_TIMER2 // tx = pin 9 - //#define IR_USE_TIMER3 // tx = pin 5 - //#define IR_USE_TIMER4 // tx = pin 6 - //#define IR_USE_TIMER5 // tx = pin 46 - -// Teensy 1.0 -#elif defined(__AVR_AT90USB162__) - #define IR_USE_TIMER1 // tx = pin 17 - -// Teensy 2.0 -#elif defined(__AVR_ATmega32U4__) - //#define IR_USE_TIMER1 // tx = pin 14 - //#define IR_USE_TIMER3 // tx = pin 9 - #define IR_USE_TIMER4_HS // tx = pin 10 - -// Teensy 3.0 / Teensy 3.1 -#elif defined(__MK20DX128__) || defined(__MK20DX256__) || defined(__MK64FX512__) || defined(__MK66FX1M0__) - #define IR_USE_TIMER_CMT // tx = pin 5 - -// Teensy-LC -#elif defined(__MKL26Z64__) - #define IR_USE_TIMER_TPM1 // tx = pin 16 - -// Teensy++ 1.0 & 2.0 -#elif defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__) - //#define IR_USE_TIMER1 // tx = pin 25 - #define IR_USE_TIMER2 // tx = pin 1 - //#define IR_USE_TIMER3 // tx = pin 16 - -// MightyCore - ATmega1284 -#elif defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__) - //#define IR_USE_TIMER1 // tx = pin 13 - #define IR_USE_TIMER2 // tx = pin 14 - //#define IR_USE_TIMER3 // tx = pin 6 - -// MightyCore - ATmega164, ATmega324, ATmega644 -#elif defined(__AVR_ATmega644__) || defined(__AVR_ATmega644P__) \ -|| defined(__AVR_ATmega324P__) || defined(__AVR_ATmega324A__) \ -|| defined(__AVR_ATmega324PA__) || defined(__AVR_ATmega164A__) \ -|| defined(__AVR_ATmega164P__) - //#define IR_USE_TIMER1 // tx = pin 13 - #define IR_USE_TIMER2 // tx = pin 14 - -//MegaCore - ATmega64, ATmega128 -#elif defined(__AVR_ATmega64__) || defined(__AVR_ATmega128__) - #define IR_USE_TIMER1 // tx = pin 13 - -// MightyCore - ATmega8535, ATmega16, ATmega32 -#elif defined(__AVR_ATmega8535__) || defined(__AVR_ATmega16__) || defined(__AVR_ATmega32__) - #define IR_USE_TIMER1 // tx = pin 13 - -// Atmega8 -#elif defined(__AVR_ATmega8__) - #define IR_USE_TIMER1 // tx = pin 9 - -// ATtiny84 -#elif defined(__AVR_ATtiny84__) - #define IR_USE_TIMER1 // tx = pin 6 - -//ATtiny85 -#elif defined(__AVR_ATtiny85__) - #define IR_USE_TIMER_TINY0 // tx = pin 1 - -#elif defined(ESP32) - #define IR_TIMER_USE_ESP32 -#else -// Arduino Duemilanove, Diecimila, LilyPad, Mini, Fio, Nano, etc -// ATmega48, ATmega88, ATmega168, ATmega328 - //#define IR_USE_TIMER1 // tx = pin 9 - #define IR_USE_TIMER2 // tx = pin 3 - -#endif - -//------------------------------------------------------------------------------ -// Defines for Timer - -//--------------------------------------------------------- -// Timer2 (8 bits) -// -#if defined(IR_USE_TIMER2) - -#define TIMER_RESET -#define TIMER_ENABLE_PWM (TCCR2A |= _BV(COM2B1)) -#define TIMER_DISABLE_PWM (TCCR2A &= ~(_BV(COM2B1))) -#define TIMER_ENABLE_INTR (TIMSK2 = _BV(OCIE2A)) -#define TIMER_DISABLE_INTR (TIMSK2 = 0) -#define TIMER_INTR_NAME TIMER2_COMPA_vect - -#define TIMER_CONFIG_KHZ(val) ({ \ - const uint8_t pwmval = SYSCLOCK / 2000 / (val); \ - TCCR2A = _BV(WGM20); \ - TCCR2B = _BV(WGM22) | _BV(CS20); \ - OCR2A = pwmval; \ - OCR2B = pwmval / 3; \ -}) - -#define TIMER_COUNT_TOP (SYSCLOCK * USECPERTICK / 1000000) - -//----------------- -#if (TIMER_COUNT_TOP < 256) -# define TIMER_CONFIG_NORMAL() ({ \ - TCCR2A = _BV(WGM21); \ - TCCR2B = _BV(CS20); \ - OCR2A = TIMER_COUNT_TOP; \ - TCNT2 = 0; \ - }) -#else -# define TIMER_CONFIG_NORMAL() ({ \ - TCCR2A = _BV(WGM21); \ - TCCR2B = _BV(CS21); \ - OCR2A = TIMER_COUNT_TOP / 8; \ - TCNT2 = 0; \ - }) -#endif - -//----------------- -#if defined(CORE_OC2B_PIN) -# define TIMER_PWM_PIN CORE_OC2B_PIN // Teensy -#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) -# define TIMER_PWM_PIN 9 // Arduino Mega -#elif defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__) \ -|| defined(__AVR_ATmega644__) || defined(__AVR_ATmega644P__) \ -|| defined(__AVR_ATmega324P__) || defined(__AVR_ATmega324A__) \ -|| defined(__AVR_ATmega324PA__) || defined(__AVR_ATmega164A__) \ -|| defined(__AVR_ATmega164P__) -# define TIMER_PWM_PIN 14 // MightyCore -#else -# define TIMER_PWM_PIN 3 // Arduino Duemilanove, Diecimila, LilyPad, etc -#endif // ATmega48, ATmega88, ATmega168, ATmega328 - -//--------------------------------------------------------- -// Timer1 (16 bits) -// -#elif defined(IR_USE_TIMER1) - -#define TIMER_RESET -#define TIMER_ENABLE_PWM (TCCR1A |= _BV(COM1A1)) -#define TIMER_DISABLE_PWM (TCCR1A &= ~(_BV(COM1A1))) - -//----------------- -#if defined(__AVR_ATmega8__) || defined(__AVR_ATmega8535__) \ -|| defined(__AVR_ATmega16__) || defined(__AVR_ATmega32__) \ -|| defined(__AVR_ATmega64__) || defined(__AVR_ATmega128__) -# define TIMER_ENABLE_INTR (TIMSK |= _BV(OCIE1A)) -# define TIMER_DISABLE_INTR (TIMSK &= ~_BV(OCIE1A)) -#else -# define TIMER_ENABLE_INTR (TIMSK1 = _BV(OCIE1A)) -# define TIMER_DISABLE_INTR (TIMSK1 = 0) -#endif - -//----------------- -#define TIMER_INTR_NAME TIMER1_COMPA_vect - -#define TIMER_CONFIG_KHZ(val) ({ \ - const uint16_t pwmval = SYSCLOCK / 2000 / (val); \ - TCCR1A = _BV(WGM11); \ - TCCR1B = _BV(WGM13) | _BV(CS10); \ - ICR1 = pwmval; \ - OCR1A = pwmval / 3; \ -}) - -#define TIMER_CONFIG_NORMAL() ({ \ - TCCR1A = 0; \ - TCCR1B = _BV(WGM12) | _BV(CS10); \ - OCR1A = SYSCLOCK * USECPERTICK / 1000000; \ - TCNT1 = 0; \ -}) - -//----------------- -#if defined(CORE_OC1A_PIN) -# define TIMER_PWM_PIN CORE_OC1A_PIN // Teensy -#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) -# define TIMER_PWM_PIN 11 // Arduino Mega -#elif defined(__AVR_ATmega64__) || defined(__AVR_ATmega128__) -# define TIMER_PWM_PIN 13 // MegaCore -#elif defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__) \ -|| defined(__AVR_ATmega644__) || defined(__AVR_ATmega644P__) \ -|| defined(__AVR_ATmega324P__) || defined(__AVR_ATmega324A__) \ -|| defined(__AVR_ATmega324PA__) || defined(__AVR_ATmega164A__) \ -|| defined(__AVR_ATmega164P__) || defined(__AVR_ATmega32__) \ -|| defined(__AVR_ATmega16__) || defined(__AVR_ATmega8535__) -# define TIMER_PWM_PIN 13 // MightyCore -#elif defined(__AVR_ATtiny84__) -# define TIMER_PWM_PIN 6 -#else -# define TIMER_PWM_PIN 9 // Arduino Duemilanove, Diecimila, LilyPad, etc -#endif // ATmega48, ATmega88, ATmega168, ATmega328 - -//--------------------------------------------------------- -// Timer3 (16 bits) -// -#elif defined(IR_USE_TIMER3) - -#define TIMER_RESET -#define TIMER_ENABLE_PWM (TCCR3A |= _BV(COM3A1)) -#define TIMER_DISABLE_PWM (TCCR3A &= ~(_BV(COM3A1))) -#define TIMER_ENABLE_INTR (TIMSK3 = _BV(OCIE3A)) -#define TIMER_DISABLE_INTR (TIMSK3 = 0) -#define TIMER_INTR_NAME TIMER3_COMPA_vect - -#define TIMER_CONFIG_KHZ(val) ({ \ - const uint16_t pwmval = SYSCLOCK / 2000 / (val); \ - TCCR3A = _BV(WGM31); \ - TCCR3B = _BV(WGM33) | _BV(CS30); \ - ICR3 = pwmval; \ - OCR3A = pwmval / 3; \ -}) - -#define TIMER_CONFIG_NORMAL() ({ \ - TCCR3A = 0; \ - TCCR3B = _BV(WGM32) | _BV(CS30); \ - OCR3A = SYSCLOCK * USECPERTICK / 1000000; \ - TCNT3 = 0; \ -}) - -//----------------- -#if defined(CORE_OC3A_PIN) -# define TIMER_PWM_PIN CORE_OC3A_PIN // Teensy -#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) -# define TIMER_PWM_PIN 5 // Arduino Mega -#elif defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__) -# define TIMER_PWM_PIN 6 // MightyCore -#else -# error "Please add OC3A pin number here\n" -#endif - -//--------------------------------------------------------- -// Timer4 (10 bits, high speed option) -// -#elif defined(IR_USE_TIMER4_HS) - -#define TIMER_RESET -#define TIMER_ENABLE_PWM (TCCR4A |= _BV(COM4A1)) -#define TIMER_DISABLE_PWM (TCCR4A &= ~(_BV(COM4A1))) -#define TIMER_ENABLE_INTR (TIMSK4 = _BV(TOIE4)) -#define TIMER_DISABLE_INTR (TIMSK4 = 0) -#define TIMER_INTR_NAME TIMER4_OVF_vect - -#define TIMER_CONFIG_KHZ(val) ({ \ - const uint16_t pwmval = SYSCLOCK / 2000 / (val); \ - TCCR4A = (1<> 8; \ - OCR4C = pwmval; \ - TC4H = (pwmval / 3) >> 8; \ - OCR4A = (pwmval / 3) & 255; \ -}) - -#define TIMER_CONFIG_NORMAL() ({ \ - TCCR4A = 0; \ - TCCR4B = _BV(CS40); \ - TCCR4C = 0; \ - TCCR4D = 0; \ - TCCR4E = 0; \ - TC4H = (SYSCLOCK * USECPERTICK / 1000000) >> 8; \ - OCR4C = (SYSCLOCK * USECPERTICK / 1000000) & 255; \ - TC4H = 0; \ - TCNT4 = 0; \ -}) - -//----------------- -#if defined(CORE_OC4A_PIN) -# define TIMER_PWM_PIN CORE_OC4A_PIN // Teensy -#elif defined(__AVR_ATmega32U4__) -# define TIMER_PWM_PIN 13 // Leonardo -#else -# error "Please add OC4A pin number here\n" -#endif - -//--------------------------------------------------------- -// Timer4 (16 bits) -// -#elif defined(IR_USE_TIMER4) - -#define TIMER_RESET -#define TIMER_ENABLE_PWM (TCCR4A |= _BV(COM4A1)) -#define TIMER_DISABLE_PWM (TCCR4A &= ~(_BV(COM4A1))) -#define TIMER_ENABLE_INTR (TIMSK4 = _BV(OCIE4A)) -#define TIMER_DISABLE_INTR (TIMSK4 = 0) -#define TIMER_INTR_NAME TIMER4_COMPA_vect - -#define TIMER_CONFIG_KHZ(val) ({ \ - const uint16_t pwmval = SYSCLOCK / 2000 / (val); \ - TCCR4A = _BV(WGM41); \ - TCCR4B = _BV(WGM43) | _BV(CS40); \ - ICR4 = pwmval; \ - OCR4A = pwmval / 3; \ -}) - -#define TIMER_CONFIG_NORMAL() ({ \ - TCCR4A = 0; \ - TCCR4B = _BV(WGM42) | _BV(CS40); \ - OCR4A = SYSCLOCK * USECPERTICK / 1000000; \ - TCNT4 = 0; \ -}) - -//----------------- -#if defined(CORE_OC4A_PIN) -# define TIMER_PWM_PIN CORE_OC4A_PIN -#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) -# define TIMER_PWM_PIN 6 // Arduino Mega -#else -# error "Please add OC4A pin number here\n" -#endif - -//--------------------------------------------------------- -// Timer5 (16 bits) -// -#elif defined(IR_USE_TIMER5) - -#define TIMER_RESET -#define TIMER_ENABLE_PWM (TCCR5A |= _BV(COM5A1)) -#define TIMER_DISABLE_PWM (TCCR5A &= ~(_BV(COM5A1))) -#define TIMER_ENABLE_INTR (TIMSK5 = _BV(OCIE5A)) -#define TIMER_DISABLE_INTR (TIMSK5 = 0) -#define TIMER_INTR_NAME TIMER5_COMPA_vect - -#define TIMER_CONFIG_KHZ(val) ({ \ - const uint16_t pwmval = SYSCLOCK / 2000 / (val); \ - TCCR5A = _BV(WGM51); \ - TCCR5B = _BV(WGM53) | _BV(CS50); \ - ICR5 = pwmval; \ - OCR5A = pwmval / 3; \ -}) - -#define TIMER_CONFIG_NORMAL() ({ \ - TCCR5A = 0; \ - TCCR5B = _BV(WGM52) | _BV(CS50); \ - OCR5A = SYSCLOCK * USECPERTICK / 1000000; \ - TCNT5 = 0; \ -}) - -//----------------- -#if defined(CORE_OC5A_PIN) -# define TIMER_PWM_PIN CORE_OC5A_PIN -#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) -# define TIMER_PWM_PIN 46 // Arduino Mega -#else -# error "Please add OC5A pin number here\n" -#endif - -//--------------------------------------------------------- -// Special carrier modulator timer -// -#elif defined(IR_USE_TIMER_CMT) - -#define TIMER_RESET ({ \ - uint8_t tmp __attribute__((unused)) = CMT_MSC; \ - CMT_CMD2 = 30; \ -}) - -#define TIMER_ENABLE_PWM do { \ - CORE_PIN5_CONFIG = PORT_PCR_MUX(2) | PORT_PCR_DSE | PORT_PCR_SRE; \ -} while(0) - -#define TIMER_DISABLE_PWM do { \ - CORE_PIN5_CONFIG = PORT_PCR_MUX(1) | PORT_PCR_DSE | PORT_PCR_SRE; \ -} while(0) - -#define TIMER_ENABLE_INTR NVIC_ENABLE_IRQ(IRQ_CMT) -#define TIMER_DISABLE_INTR NVIC_DISABLE_IRQ(IRQ_CMT) -#define TIMER_INTR_NAME cmt_isr - -//----------------- -#ifdef ISR -# undef ISR -#endif -#define ISR(f) void f(void) - -//----------------- -#define CMT_PPS_DIV ((F_BUS + 7999999) / 8000000) -#if F_BUS < 8000000 -#error IRremote requires at least 8 MHz on Teensy 3.x -#endif - -//----------------- -#define TIMER_CONFIG_KHZ(val) ({ \ - SIM_SCGC4 |= SIM_SCGC4_CMT; \ - SIM_SOPT2 |= SIM_SOPT2_PTD7PAD; \ - CMT_PPS = CMT_PPS_DIV - 1; \ - CMT_CGH1 = ((F_BUS / CMT_PPS_DIV / 3000) + ((val)/2)) / (val); \ - CMT_CGL1 = ((F_BUS / CMT_PPS_DIV / 1500) + ((val)/2)) / (val); \ - CMT_CMD1 = 0; \ - CMT_CMD2 = 30; \ - CMT_CMD3 = 0; \ - CMT_CMD4 = 0; \ - CMT_OC = 0x60; \ - CMT_MSC = 0x01; \ -}) - -#define TIMER_CONFIG_NORMAL() ({ \ - SIM_SCGC4 |= SIM_SCGC4_CMT; \ - CMT_PPS = CMT_PPS_DIV - 1; \ - CMT_CGH1 = 1; \ - CMT_CGL1 = 1; \ - CMT_CMD1 = 0; \ - CMT_CMD2 = 30; \ - CMT_CMD3 = 0; \ - CMT_CMD4 = (F_BUS / 160000 + CMT_PPS_DIV / 2) / CMT_PPS_DIV - 31; \ - CMT_OC = 0; \ - CMT_MSC = 0x03; \ -}) - -#define TIMER_PWM_PIN 5 - -// defines for TPM1 timer on Teensy-LC -#elif defined(IR_USE_TIMER_TPM1) -#define TIMER_RESET FTM1_SC |= FTM_SC_TOF; -#define TIMER_ENABLE_PWM CORE_PIN16_CONFIG = PORT_PCR_MUX(3)|PORT_PCR_DSE|PORT_PCR_SRE -#define TIMER_DISABLE_PWM CORE_PIN16_CONFIG = PORT_PCR_MUX(1)|PORT_PCR_SRE -#define TIMER_ENABLE_INTR NVIC_ENABLE_IRQ(IRQ_FTM1) -#define TIMER_DISABLE_INTR NVIC_DISABLE_IRQ(IRQ_FTM1) -#define TIMER_INTR_NAME ftm1_isr -#ifdef ISR -#undef ISR -#endif -#define ISR(f) void f(void) -#define TIMER_CONFIG_KHZ(val) ({ \ - SIM_SCGC6 |= SIM_SCGC6_TPM1; \ - FTM1_SC = 0; \ - FTM1_CNT = 0; \ - FTM1_MOD = (F_PLL/2000) / val - 1; \ - FTM1_C0V = (F_PLL/6000) / val - 1; \ - FTM1_SC = FTM_SC_CLKS(1) | FTM_SC_PS(0); \ -}) -#define TIMER_CONFIG_NORMAL() ({ \ - SIM_SCGC6 |= SIM_SCGC6_TPM1; \ - FTM1_SC = 0; \ - FTM1_CNT = 0; \ - FTM1_MOD = (F_PLL/40000) - 1; \ - FTM1_C0V = 0; \ - FTM1_SC = FTM_SC_CLKS(1) | FTM_SC_PS(0) | FTM_SC_TOF | FTM_SC_TOIE; \ -}) -#define TIMER_PWM_PIN 16 - -// defines for timer_tiny0 (8 bits) -#elif defined(IR_USE_TIMER_TINY0) -#define TIMER_RESET -#define TIMER_ENABLE_PWM (TCCR0A |= _BV(COM0B1)) -#define TIMER_DISABLE_PWM (TCCR0A &= ~(_BV(COM0B1))) -#define TIMER_ENABLE_INTR (TIMSK |= _BV(OCIE0A)) -#define TIMER_DISABLE_INTR (TIMSK &= ~(_BV(OCIE0A))) -#define TIMER_INTR_NAME TIMER0_COMPA_vect -#define TIMER_CONFIG_KHZ(val) ({ \ - const uint8_t pwmval = SYSCLOCK / 2000 / (val); \ - TCCR0A = _BV(WGM00); \ - TCCR0B = _BV(WGM02) | _BV(CS00); \ - OCR0A = pwmval; \ - OCR0B = pwmval / 3; \ -}) -#define TIMER_COUNT_TOP (SYSCLOCK * USECPERTICK / 1000000) -#if (TIMER_COUNT_TOP < 256) -#define TIMER_CONFIG_NORMAL() ({ \ - TCCR0A = _BV(WGM01); \ - TCCR0B = _BV(CS00); \ - OCR0A = TIMER_COUNT_TOP; \ - TCNT0 = 0; \ -}) -#else -#define TIMER_CONFIG_NORMAL() ({ \ - TCCR0A = _BV(WGM01); \ - TCCR0B = _BV(CS01); \ - OCR0A = TIMER_COUNT_TOP / 8; \ - TCNT0 = 0; \ -}) -#endif - -#define TIMER_PWM_PIN 1 /* ATtiny85 */ - -//--------------------------------------------------------- -// ESP32 (ESP8266 should likely be added here too) -// - -// ESP32 has it own timer API and does not use these macros, but to avoid ifdef'ing -// them out in the common code, they are defined to no-op. This allows the code to compile -// (which it wouldn't otherwise) but irsend will not work until ESP32 specific code is written -// for that -- merlin -// As a warning, sending timing specific code from an ESP32 can be challenging if you need 100% -// reliability because the arduino code may be interrupted and cause your sent waveform to be the -// wrong length. This is specifically an issue for neopixels which require 800Khz resolution. -// IR may just work as is with the common code since it's lower frequency, but if not, the other -// way to do this on ESP32 is using the RMT built in driver like in this incomplete library below -// https://github.com/ExploreEmbedded/ESP32_RMT -#elif defined(IR_TIMER_USE_ESP32) -#define TIMER_RESET -#define TIMER_ENABLE_PWM -#define TIMER_DISABLE_PWM Serial.println("IRsend not implemented for ESP32 yet"); -#define TIMER_ENABLE_INTR -#define TIMER_DISABLE_INTR -#define TIMER_INTR_NAME - -//--------------------------------------------------------- -// Unknown Timer -// -#else -# error "Internal code configuration error, no known IR_USE_TIMER# defined\n" -#endif - -#endif // ! boarddefs_h diff --git a/lib/Arduino-IRremote/changelog.md b/lib/Arduino-IRremote/changelog.md deleted file mode 100644 index 81339f2e..00000000 --- a/lib/Arduino-IRremote/changelog.md +++ /dev/null @@ -1,78 +0,0 @@ -## 2.3.3 - 2017/03/31 -- Added ESP32 IR receive support [PR #427](https://github.com/z3t0/Arduino-IRremote/pull/425) - -## 2.2.3 - 2017/03/27 -- Fix calculation of pause length in LEGO PF protocol [PR #427](https://github.com/z3t0/Arduino-IRremote/pull/427) - -## 2.2.2 - 2017/01/20 -- Fixed naming bug [PR #398](https://github.com/z3t0/Arduino-IRremote/pull/398) - -## 2.2.1 - 2016/07/27 -- Added tests for Lego Power Functions Protocol [PR #336](https://github.com/z3t0/Arduino-IRremote/pull/336) - -## 2.2.0 - 2016/06/28 -- Added support for ATmega8535 -- Added support for ATmega16 -- Added support for ATmega32 -- Added support for ATmega164 -- Added support for ATmega324 -- Added support for ATmega644 -- Added support for ATmega1284 -- Added support for ATmega64 -- Added support for ATmega128 - -[PR](https://github.com/z3t0/Arduino-IRremote/pull/324) - -## 2.1.1 - 2016/05/04 -- Added Lego Power Functions Protocol [PR #309](https://github.com/z3t0/Arduino-IRremote/pull/309) - -## 2.1.0 - 2016/02/20 -- Improved Debugging [PR #258](https://github.com/z3t0/Arduino-IRremote/pull/258) -- Display TIME instead of TICKS [PR #258](https://github.com/z3t0/Arduino-IRremote/pull/258) - -## 2.0.4 - 2016/02/20 -- Add Panasonic and JVC to IRrecord example [PR](https://github.com/z3t0/Arduino-IRremote/pull/54) - -## 2.0.3 - 2016/02/20 -- Change IRSend Raw parameter to const [PR](https://github.com/z3t0/Arduino-IRremote/pull/227) - -## 2.0.2 - 2015/12/02 -- Added IRremoteInfo Sketch - [PR](https://github.com/z3t0/Arduino-IRremote/pull/241) -- Enforcing changelog.md - -## 2.0.1 - 2015/07/26 - [Release](https://github.com/shirriff/Arduino-IRremote/releases/tag/BETA) -### Changes -- Updated README -- Updated Contributors -- Fixed #110 Mess -- Created Gitter Room -- Added Gitter Badge -- Standardised Code Base -- Clean Debug Output -- Optimized Send Loops -- Modularized Design -- Optimized and Updated Examples -- Improved Documentation -- Fixed and Improved many coding errors -- Fixed Aiwa RC-T501 Decoding -- Fixed Interrupt on ATmega8 -- Switched to Stable Release of @PlatformIO - -### Additions -- Added Aiwa RC-T501 Protocol -- Added Denon Protocol -- Added Pronto Support -- Added Library Properties -- Added Template For New Protocols -- Added this changelog -- Added Teensy LC Support -- Added ATtiny84 Support -- Added ATtiny85 Support -- Added isIdle method - -### Deletions -- Removed (Fixed) #110 -- Broke Teensy 3 / 3.1 Support - -### Not Working -- Teensy 3 / 3.1 Support is in Development diff --git a/lib/Arduino-IRremote/examples/AiwaRCT501SendDemo/AiwaRCT501SendDemo.ino b/lib/Arduino-IRremote/examples/AiwaRCT501SendDemo/AiwaRCT501SendDemo.ino deleted file mode 100644 index 5a9862bf..00000000 --- a/lib/Arduino-IRremote/examples/AiwaRCT501SendDemo/AiwaRCT501SendDemo.ino +++ /dev/null @@ -1,26 +0,0 @@ -/* - * IRremote: IRsendDemo - demonstrates sending IR codes with IRsend - * An IR LED must be connected to Arduino PWM pin 3. - * Version 0.1 July, 2009 - * Copyright 2009 Ken Shirriff - * http://arcfn.com - */ - -#include "IRremote.h" - -#define POWER 0x7F80 -#define AIWA_RC_T501 - -IRsend irsend; - -void setup() { - Serial.begin(9600); - Serial.println("Arduino Ready"); -} - -void loop() { - if (Serial.read() != -1) { - irsend.sendAiwaRCT501(POWER); - delay(60); // Optional - } -} diff --git a/lib/Arduino-IRremote/examples/IRrecord/IRrecord.ino b/lib/Arduino-IRremote/examples/IRrecord/IRrecord.ino deleted file mode 100644 index a121e590..00000000 --- a/lib/Arduino-IRremote/examples/IRrecord/IRrecord.ino +++ /dev/null @@ -1,183 +0,0 @@ -/* - * IRrecord: record and play back IR signals as a minimal - * An IR detector/demodulator must be connected to the input RECV_PIN. - * An IR LED must be connected to the output PWM pin 3. - * A button must be connected to the input BUTTON_PIN; this is the - * send button. - * A visible LED can be connected to STATUS_PIN to provide status. - * - * The logic is: - * If the button is pressed, send the IR code. - * If an IR code is received, record it. - * - * Version 0.11 September, 2009 - * Copyright 2009 Ken Shirriff - * http://arcfn.com - */ - -#include - -int RECV_PIN = 11; -int BUTTON_PIN = 12; -int STATUS_PIN = 13; - -IRrecv irrecv(RECV_PIN); -IRsend irsend; - -decode_results results; - -void setup() -{ - Serial.begin(9600); - irrecv.enableIRIn(); // Start the receiver - pinMode(BUTTON_PIN, INPUT); - pinMode(STATUS_PIN, OUTPUT); -} - -// Storage for the recorded code -int codeType = -1; // The type of code -unsigned long codeValue; // The code value if not raw -unsigned int rawCodes[RAWBUF]; // The durations if raw -int codeLen; // The length of the code -int toggle = 0; // The RC5/6 toggle state - -// Stores the code for later playback -// Most of this code is just logging -void storeCode(decode_results *results) { - codeType = results->decode_type; - //int count = results->rawlen; - if (codeType == UNKNOWN) { - Serial.println("Received unknown code, saving as raw"); - codeLen = results->rawlen - 1; - // To store raw codes: - // Drop first value (gap) - // Convert from ticks to microseconds - // Tweak marks shorter, and spaces longer to cancel out IR receiver distortion - for (int i = 1; i <= codeLen; i++) { - if (i % 2) { - // Mark - rawCodes[i - 1] = results->rawbuf[i]*USECPERTICK - MARK_EXCESS; - Serial.print(" m"); - } - else { - // Space - rawCodes[i - 1] = results->rawbuf[i]*USECPERTICK + MARK_EXCESS; - Serial.print(" s"); - } - Serial.print(rawCodes[i - 1], DEC); - } - Serial.println(""); - } - else { - if (codeType == NEC) { - Serial.print("Received NEC: "); - if (results->value == REPEAT) { - // Don't record a NEC repeat value as that's useless. - Serial.println("repeat; ignoring."); - return; - } - } - else if (codeType == SONY) { - Serial.print("Received SONY: "); - } - else if (codeType == PANASONIC) { - Serial.print("Received PANASONIC: "); - } - else if (codeType == JVC) { - Serial.print("Received JVC: "); - } - else if (codeType == RC5) { - Serial.print("Received RC5: "); - } - else if (codeType == RC6) { - Serial.print("Received RC6: "); - } - else { - Serial.print("Unexpected codeType "); - Serial.print(codeType, DEC); - Serial.println(""); - } - Serial.println(results->value, HEX); - codeValue = results->value; - codeLen = results->bits; - } -} - -void sendCode(int repeat) { - if (codeType == NEC) { - if (repeat) { - irsend.sendNEC(REPEAT, codeLen); - Serial.println("Sent NEC repeat"); - } - else { - irsend.sendNEC(codeValue, codeLen); - Serial.print("Sent NEC "); - Serial.println(codeValue, HEX); - } - } - else if (codeType == SONY) { - irsend.sendSony(codeValue, codeLen); - Serial.print("Sent Sony "); - Serial.println(codeValue, HEX); - } - else if (codeType == PANASONIC) { - irsend.sendPanasonic(codeValue, codeLen); - Serial.print("Sent Panasonic"); - Serial.println(codeValue, HEX); - } - else if (codeType == JVC) { - irsend.sendJVC(codeValue, codeLen, false); - Serial.print("Sent JVC"); - Serial.println(codeValue, HEX); - } - else if (codeType == RC5 || codeType == RC6) { - if (!repeat) { - // Flip the toggle bit for a new button press - toggle = 1 - toggle; - } - // Put the toggle bit into the code to send - codeValue = codeValue & ~(1 << (codeLen - 1)); - codeValue = codeValue | (toggle << (codeLen - 1)); - if (codeType == RC5) { - Serial.print("Sent RC5 "); - Serial.println(codeValue, HEX); - irsend.sendRC5(codeValue, codeLen); - } - else { - irsend.sendRC6(codeValue, codeLen); - Serial.print("Sent RC6 "); - Serial.println(codeValue, HEX); - } - } - else if (codeType == UNKNOWN /* i.e. raw */) { - // Assume 38 KHz - irsend.sendRaw(rawCodes, codeLen, 38); - Serial.println("Sent raw"); - } -} - -int lastButtonState; - -void loop() { - // If button pressed, send the code. - int buttonState = digitalRead(BUTTON_PIN); - if (lastButtonState == HIGH && buttonState == LOW) { - Serial.println("Released"); - irrecv.enableIRIn(); // Re-enable receiver - } - - if (buttonState) { - Serial.println("Pressed, sending"); - digitalWrite(STATUS_PIN, HIGH); - sendCode(lastButtonState == buttonState); - digitalWrite(STATUS_PIN, LOW); - delay(50); // Wait a bit between retransmissions - } - else if (irrecv.decode(&results)) { - digitalWrite(STATUS_PIN, HIGH); - storeCode(&results); - irrecv.resume(); // resume receiver - digitalWrite(STATUS_PIN, LOW); - } - lastButtonState = buttonState; -} diff --git a/lib/Arduino-IRremote/examples/IRrecvDemo/IRrecvDemo.ino b/lib/Arduino-IRremote/examples/IRrecvDemo/IRrecvDemo.ino deleted file mode 100644 index 3e2d280e..00000000 --- a/lib/Arduino-IRremote/examples/IRrecvDemo/IRrecvDemo.ino +++ /dev/null @@ -1,33 +0,0 @@ -/* - * IRremote: IRrecvDemo - demonstrates receiving IR codes with IRrecv - * An IR detector/demodulator must be connected to the input RECV_PIN. - * Version 0.1 July, 2009 - * Copyright 2009 Ken Shirriff - * http://arcfn.com - */ - -#include - -int RECV_PIN = 11; - -IRrecv irrecv(RECV_PIN); - -decode_results results; - -void setup() -{ - Serial.begin(9600); - // In case the interrupt driver crashes on setup, give a clue - // to the user what's going on. - Serial.println("Enabling IRin"); - irrecv.enableIRIn(); // Start the receiver - Serial.println("Enabled IRin"); -} - -void loop() { - if (irrecv.decode(&results)) { - Serial.println(results.value, HEX); - irrecv.resume(); // Receive the next value - } - delay(100); -} diff --git a/lib/Arduino-IRremote/examples/IRrecvDump/IRrecvDump.ino b/lib/Arduino-IRremote/examples/IRrecvDump/IRrecvDump.ino deleted file mode 100644 index fa25cd8e..00000000 --- a/lib/Arduino-IRremote/examples/IRrecvDump/IRrecvDump.ino +++ /dev/null @@ -1,95 +0,0 @@ -/* - * IRremote: IRrecvDump - dump details of IR codes with IRrecv - * An IR detector/demodulator must be connected to the input RECV_PIN. - * Version 0.1 July, 2009 - * Copyright 2009 Ken Shirriff - * http://arcfn.com - * JVC and Panasonic protocol added by Kristian Lauszus (Thanks to zenwheel and other people at the original blog post) - * LG added by Darryl Smith (based on the JVC protocol) - */ - -#include - -/* -* Default is Arduino pin D11. -* You can change this to another available Arduino Pin. -* Your IR receiver should be connected to the pin defined here -*/ -int RECV_PIN = 11; - -IRrecv irrecv(RECV_PIN); - -decode_results results; - -void setup() -{ - Serial.begin(9600); - irrecv.enableIRIn(); // Start the receiver -} - - -void dump(decode_results *results) { - // Dumps out the decode_results structure. - // Call this after IRrecv::decode() - int count = results->rawlen; - if (results->decode_type == UNKNOWN) { - Serial.print("Unknown encoding: "); - } - else if (results->decode_type == NEC) { - Serial.print("Decoded NEC: "); - - } - else if (results->decode_type == SONY) { - Serial.print("Decoded SONY: "); - } - else if (results->decode_type == RC5) { - Serial.print("Decoded RC5: "); - } - else if (results->decode_type == RC6) { - Serial.print("Decoded RC6: "); - } - else if (results->decode_type == PANASONIC) { - Serial.print("Decoded PANASONIC - Address: "); - Serial.print(results->address, HEX); - Serial.print(" Value: "); - } - else if (results->decode_type == LG) { - Serial.print("Decoded LG: "); - } - else if (results->decode_type == JVC) { - Serial.print("Decoded JVC: "); - } - else if (results->decode_type == AIWA_RC_T501) { - Serial.print("Decoded AIWA RC T501: "); - } - else if (results->decode_type == WHYNTER) { - Serial.print("Decoded Whynter: "); - } - Serial.print(results->value, HEX); - Serial.print(" ("); - Serial.print(results->bits, DEC); - Serial.println(" bits)"); - Serial.print("Raw ("); - Serial.print(count, DEC); - Serial.print("): "); - - for (int i = 1; i < count; i++) { - if (i & 1) { - Serial.print(results->rawbuf[i]*USECPERTICK, DEC); - } - else { - Serial.write('-'); - Serial.print((unsigned long) results->rawbuf[i]*USECPERTICK, DEC); - } - Serial.print(" "); - } - Serial.println(); -} - -void loop() { - if (irrecv.decode(&results)) { - Serial.println(results.value, HEX); - dump(&results); - irrecv.resume(); // Receive the next value - } -} diff --git a/lib/Arduino-IRremote/examples/IRrecvDumpV2/IRrecvDumpV2.ino b/lib/Arduino-IRremote/examples/IRrecvDumpV2/IRrecvDumpV2.ino deleted file mode 100644 index 72561273..00000000 --- a/lib/Arduino-IRremote/examples/IRrecvDumpV2/IRrecvDumpV2.ino +++ /dev/null @@ -1,177 +0,0 @@ -//------------------------------------------------------------------------------ -// Include the IRremote library header -// -#include - -//------------------------------------------------------------------------------ -// Tell IRremote which Arduino pin is connected to the IR Receiver (TSOP4838) -// -int recvPin = 11; -IRrecv irrecv(recvPin); - -//+============================================================================= -// Configure the Arduino -// -void setup ( ) -{ - Serial.begin(9600); // Status message will be sent to PC at 9600 baud - irrecv.enableIRIn(); // Start the receiver -} - -//+============================================================================= -// Display IR code -// -void ircode (decode_results *results) -{ - // Panasonic has an Address - if (results->decode_type == PANASONIC) { - Serial.print(results->address, HEX); - Serial.print(":"); - } - - // Print Code - Serial.print(results->value, HEX); -} - -//+============================================================================= -// Display encoding type -// -void encoding (decode_results *results) -{ - switch (results->decode_type) { - default: - case UNKNOWN: Serial.print("UNKNOWN"); break ; - case NEC: Serial.print("NEC"); break ; - case SONY: Serial.print("SONY"); break ; - case RC5: Serial.print("RC5"); break ; - case RC6: Serial.print("RC6"); break ; - case DISH: Serial.print("DISH"); break ; - case SHARP: Serial.print("SHARP"); break ; - case JVC: Serial.print("JVC"); break ; - case SANYO: Serial.print("SANYO"); break ; - case MITSUBISHI: Serial.print("MITSUBISHI"); break ; - case SAMSUNG: Serial.print("SAMSUNG"); break ; - case LG: Serial.print("LG"); break ; - case WHYNTER: Serial.print("WHYNTER"); break ; - case AIWA_RC_T501: Serial.print("AIWA_RC_T501"); break ; - case PANASONIC: Serial.print("PANASONIC"); break ; - case DENON: Serial.print("Denon"); break ; - } -} - -//+============================================================================= -// Dump out the decode_results structure. -// -void dumpInfo (decode_results *results) -{ - // Check if the buffer overflowed - if (results->overflow) { - Serial.println("IR code too long. Edit IRremoteInt.h and increase RAWBUF"); - return; - } - - // Show Encoding standard - Serial.print("Encoding : "); - encoding(results); - Serial.println(""); - - // Show Code & length - Serial.print("Code : "); - ircode(results); - Serial.print(" ("); - Serial.print(results->bits, DEC); - Serial.println(" bits)"); -} - -//+============================================================================= -// Dump out the decode_results structure. -// -void dumpRaw (decode_results *results) -{ - // Print Raw data - Serial.print("Timing["); - Serial.print(results->rawlen-1, DEC); - Serial.println("]: "); - - for (int i = 1; i < results->rawlen; i++) { - unsigned long x = results->rawbuf[i] * USECPERTICK; - if (!(i & 1)) { // even - Serial.print("-"); - if (x < 1000) Serial.print(" ") ; - if (x < 100) Serial.print(" ") ; - Serial.print(x, DEC); - } else { // odd - Serial.print(" "); - Serial.print("+"); - if (x < 1000) Serial.print(" ") ; - if (x < 100) Serial.print(" ") ; - Serial.print(x, DEC); - if (i < results->rawlen-1) Serial.print(", "); //',' not needed for last one - } - if (!(i % 8)) Serial.println(""); - } - Serial.println(""); // Newline -} - -//+============================================================================= -// Dump out the decode_results structure. -// -void dumpCode (decode_results *results) -{ - // Start declaration - Serial.print("unsigned int "); // variable type - Serial.print("rawData["); // array name - Serial.print(results->rawlen - 1, DEC); // array size - Serial.print("] = {"); // Start declaration - - // Dump data - for (int i = 1; i < results->rawlen; i++) { - Serial.print(results->rawbuf[i] * USECPERTICK, DEC); - if ( i < results->rawlen-1 ) Serial.print(","); // ',' not needed on last one - if (!(i & 1)) Serial.print(" "); - } - - // End declaration - Serial.print("};"); // - - // Comment - Serial.print(" // "); - encoding(results); - Serial.print(" "); - ircode(results); - - // Newline - Serial.println(""); - - // Now dump "known" codes - if (results->decode_type != UNKNOWN) { - - // Some protocols have an address - if (results->decode_type == PANASONIC) { - Serial.print("unsigned int addr = 0x"); - Serial.print(results->address, HEX); - Serial.println(";"); - } - - // All protocols have data - Serial.print("unsigned int data = 0x"); - Serial.print(results->value, HEX); - Serial.println(";"); - } -} - -//+============================================================================= -// The repeating section of the code -// -void loop ( ) -{ - decode_results results; // Somewhere to store the results - - if (irrecv.decode(&results)) { // Grab an IR code - dumpInfo(&results); // Output the results - dumpRaw(&results); // Output the results in RAW format - dumpCode(&results); // Output the results as source code - Serial.println(""); // Blank line between entries - irrecv.resume(); // Prepare for the next value - } -} diff --git a/lib/Arduino-IRremote/examples/IRrelay/IRrelay.ino b/lib/Arduino-IRremote/examples/IRrelay/IRrelay.ino deleted file mode 100644 index 046fb5fa..00000000 --- a/lib/Arduino-IRremote/examples/IRrelay/IRrelay.ino +++ /dev/null @@ -1,85 +0,0 @@ -/* - * IRremote: IRrecvDemo - demonstrates receiving IR codes with IRrecv - * An IR detector/demodulator must be connected to the input RECV_PIN. - * Version 0.1 July, 2009 - * Copyright 2009 Ken Shirriff - * http://arcfn.com - */ - -#include - -int RECV_PIN = 11; -int RELAY_PIN = 4; - -IRrecv irrecv(RECV_PIN); -decode_results results; - -// Dumps out the decode_results structure. -// Call this after IRrecv::decode() -// void * to work around compiler issue -//void dump(void *v) { -// decode_results *results = (decode_results *)v -void dump(decode_results *results) { - int count = results->rawlen; - if (results->decode_type == UNKNOWN) { - Serial.println("Could not decode message"); - } - else { - if (results->decode_type == NEC) { - Serial.print("Decoded NEC: "); - } - else if (results->decode_type == SONY) { - Serial.print("Decoded SONY: "); - } - else if (results->decode_type == RC5) { - Serial.print("Decoded RC5: "); - } - else if (results->decode_type == RC6) { - Serial.print("Decoded RC6: "); - } - Serial.print(results->value, HEX); - Serial.print(" ("); - Serial.print(results->bits, DEC); - Serial.println(" bits)"); - } - Serial.print("Raw ("); - Serial.print(count, DEC); - Serial.print("): "); - - for (int i = 0; i < count; i++) { - if ((i % 2) == 1) { - Serial.print(results->rawbuf[i]*USECPERTICK, DEC); - } - else { - Serial.print(-(int)results->rawbuf[i]*USECPERTICK, DEC); - } - Serial.print(" "); - } - Serial.println(""); -} - -void setup() -{ - pinMode(RELAY_PIN, OUTPUT); - pinMode(13, OUTPUT); - Serial.begin(9600); - irrecv.enableIRIn(); // Start the receiver -} - -int on = 0; -unsigned long last = millis(); - -void loop() { - if (irrecv.decode(&results)) { - // If it's been at least 1/4 second since the last - // IR received, toggle the relay - if (millis() - last > 250) { - on = !on; - digitalWrite(RELAY_PIN, on ? HIGH : LOW); - digitalWrite(13, on ? HIGH : LOW); - dump(&results); - } - last = millis(); - irrecv.resume(); // Receive the next value - } -} diff --git a/lib/Arduino-IRremote/examples/IRremoteInfo/IRremoteInfo.ino b/lib/Arduino-IRremote/examples/IRremoteInfo/IRremoteInfo.ino deleted file mode 100644 index 2a269d94..00000000 --- a/lib/Arduino-IRremote/examples/IRremoteInfo/IRremoteInfo.ino +++ /dev/null @@ -1,230 +0,0 @@ -/* - * IRremote: IRremoteInfo - prints relevant config info & settings for IRremote over serial - * Intended to help identify & troubleshoot the various settings of IRremote - * For example, sometimes users are unsure of which pin is used for Tx or the RAWBUF values - * This example can be used to assist the user directly or with support. - * Intended to help identify & troubleshoot the various settings of IRremote - * Hopefully this utility will be a useful tool for support & troubleshooting for IRremote - * Check out the blog post describing the sketch via http://www.analysir.com/blog/2015/11/28/helper-utility-for-troubleshooting-irremote/ - * Version 1.0 November 2015 - * Original Author: AnalysIR - IR software & modules for Makers & Pros, visit http://www.AnalysIR.com - */ - - -#include - -void setup() -{ - Serial.begin(115200); //You may alter the BAUD rate here as needed - while (!Serial); //wait until Serial is established - required on some Platforms - - //Runs only once per restart of the Arduino. - dumpHeader(); - dumpRAWBUF(); - dumpTIMER(); - dumpTimerPin(); - dumpClock(); - dumpPlatform(); - dumpPulseParams(); - dumpSignalParams(); - dumpArduinoIDE(); - dumpDebugMode(); - dumpProtocols(); - dumpFooter(); -} - -void loop() { - //nothing to do! -} - -void dumpRAWBUF() { - Serial.print(F("RAWBUF: ")); - Serial.println(RAWBUF); -} - -void dumpTIMER() { - boolean flag = false; -#ifdef IR_USE_TIMER1 - Serial.print(F("Timer defined for use: ")); Serial.println(F("Timer1")); flag = true; -#endif -#ifdef IR_USE_TIMER2 - Serial.print(F("Timer defined for use: ")); Serial.println(F("Timer2")); flag = true; -#endif -#ifdef IR_USE_TIMER3 - Serial.print(F("Timer defined for use: ")); Serial.println(F("Timer3")); flag = true; -#endif -#ifdef IR_USE_TIMER4 - Serial.print(F("Timer defined for use: ")); Serial.println(F("Timer4")); flag = true; -#endif -#ifdef IR_USE_TIMER5 - Serial.print(F("Timer defined for use: ")); Serial.println(F("Timer5")); flag = true; -#endif -#ifdef IR_USE_TIMER4_HS - Serial.print(F("Timer defined for use: ")); Serial.println(F("Timer4_HS")); flag = true; -#endif -#ifdef IR_USE_TIMER_CMT - Serial.print(F("Timer defined for use: ")); Serial.println(F("Timer_CMT")); flag = true; -#endif -#ifdef IR_USE_TIMER_TPM1 - Serial.print(F("Timer defined for use: ")); Serial.println(F("Timer_TPM1")); flag = true; -#endif -#ifdef IR_USE_TIMER_TINY0 - Serial.print(F("Timer defined for use: ")); Serial.println(F("Timer_TINY0")); flag = true; -#endif - - if (!flag) { - Serial.print(F("Timer Error: ")); Serial.println(F("not defined")); - } -} - -void dumpTimerPin() { - Serial.print(F("IR Tx Pin: ")); - Serial.println(TIMER_PWM_PIN); -} - -void dumpClock() { - Serial.print(F("MCU Clock: ")); - Serial.println(F_CPU); -} - -void dumpPlatform() { - Serial.print(F("MCU Platform: ")); - -#if defined(__AVR_ATmega1280__) - Serial.println(F("Arduino Mega1280")); -#elif defined(__AVR_ATmega2560__) - Serial.println(F("Arduino Mega2560")); -#elif defined(__AVR_AT90USB162__) - Serial.println(F("Teensy 1.0 / AT90USB162")); - // Teensy 2.0 -#elif defined(__AVR_ATmega32U4__) - Serial.println(F("Arduino Leonardo / Yun / Teensy 1.0 / ATmega32U4")); -#elif defined(__MK20DX128__) || defined(__MK20DX256__) - Serial.println(F("Teensy 3.0 / Teensy 3.1 / MK20DX128 / MK20DX256")); -#elif defined(__MKL26Z64__) - Serial.println(F("Teensy-LC / MKL26Z64")); -#elif defined(__AVR_AT90USB646__) - Serial.println(F("Teensy++ 1.0 / AT90USB646")); -#elif defined(__AVR_AT90USB1286__) - Serial.println(F("Teensy++ 2.0 / AT90USB1286")); -#elif defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__) - Serial.println(F("ATmega1284")); -#elif defined(__AVR_ATmega644__) || defined(__AVR_ATmega644P__) - Serial.println(F("ATmega644")); -#elif defined(__AVR_ATmega324P__) || defined(__AVR_ATmega324A__) || defined(__AVR_ATmega324PA__) - Serial.println(F("ATmega324")); -#elif defined(__AVR_ATmega164A__) || defined(__AVR_ATmega164P__) - Serial.println(F("ATmega164")); -#elif defined(__AVR_ATmega128__) - Serial.println(F("ATmega128")); -#elif defined(__AVR_ATmega88__) || defined(__AVR_ATmega88P__) - Serial.println(F("ATmega88")); -#elif defined(__AVR_ATmega64__) - Serial.println(F("ATmega64")); -#elif defined(__AVR_ATmega48__) || defined(__AVR_ATmega48P__) - Serial.println(F("ATmega48")); -#elif defined(__AVR_ATmega32__) - Serial.println(F("ATmega32")); -#elif defined(__AVR_ATmega16__) - Serial.println(F("ATmega16")); -#elif defined(__AVR_ATmega8535__) - Serial.println(F("ATmega8535")); -#elif defined(__AVR_ATmega8__) - Serial.println(F("Atmega8")); -#elif defined(__AVR_ATtiny84__) - Serial.println(F("ATtiny84")); -#elif defined(__AVR_ATtiny85__) - Serial.println(F("ATtiny85")); -#else - Serial.println(F("ATmega328(P) / (Duemilanove, Diecimila, LilyPad, Mini, Micro, Fio, Nano, etc)")); -#endif -} - -void dumpPulseParams() { - Serial.print(F("Mark Excess: ")); Serial.print(MARK_EXCESS);; Serial.println(F(" uSecs")); - Serial.print(F("Microseconds per tick: ")); Serial.print(USECPERTICK);; Serial.println(F(" uSecs")); - Serial.print(F("Measurement tolerance: ")); Serial.print(TOLERANCE); Serial.println(F("%")); -} - -void dumpSignalParams() { - Serial.print(F("Minimum Gap between IR Signals: ")); Serial.print(_GAP); Serial.println(F(" uSecs")); -} - -void dumpDebugMode() { - Serial.print(F("Debug Mode: ")); -#if DEBUG - Serial.println(F("ON")); -#else - Serial.println(F("OFF (Normal)")); -#endif - -} - -void dumpArduinoIDE() { - Serial.print(F("Arduino IDE version: ")); - Serial.print(ARDUINO / 10000); - Serial.write('.'); - Serial.print((ARDUINO % 10000) / 100); - Serial.write('.'); - Serial.println(ARDUINO % 100); -} - -void dumpProtocols() { - - Serial.println(); Serial.print(F("IR PROTOCOLS ")); Serial.print(F("SEND ")); Serial.println(F("DECODE")); - Serial.print(F("============= ")); Serial.print(F("======== ")); Serial.println(F("========")); - Serial.print(F("RC5: ")); printSendEnabled(SEND_RC5); printDecodeEnabled(DECODE_RC6); - Serial.print(F("RC6: ")); printSendEnabled(SEND_RC6); printDecodeEnabled(DECODE_RC5); - Serial.print(F("NEC: ")); printSendEnabled(SEND_NEC); printDecodeEnabled(DECODE_NEC); - Serial.print(F("SONY: ")); printSendEnabled(SEND_SONY); printDecodeEnabled(DECODE_SONY); - Serial.print(F("PANASONIC: ")); printSendEnabled(SEND_PANASONIC); printDecodeEnabled(DECODE_PANASONIC); - Serial.print(F("JVC: ")); printSendEnabled(SEND_JVC); printDecodeEnabled(DECODE_JVC); - Serial.print(F("SAMSUNG: ")); printSendEnabled(SEND_SAMSUNG); printDecodeEnabled(DECODE_SAMSUNG); - Serial.print(F("WHYNTER: ")); printSendEnabled(SEND_WHYNTER); printDecodeEnabled(DECODE_WHYNTER); - Serial.print(F("AIWA_RC_T501: ")); printSendEnabled(SEND_AIWA_RC_T501); printDecodeEnabled(DECODE_AIWA_RC_T501); - Serial.print(F("LG: ")); printSendEnabled(SEND_LG); printDecodeEnabled(DECODE_LG); - Serial.print(F("SANYO: ")); printSendEnabled(SEND_SANYO); printDecodeEnabled(DECODE_SANYO); - Serial.print(F("MITSUBISHI: ")); printSendEnabled(SEND_MITSUBISHI); printDecodeEnabled(DECODE_MITSUBISHI); - Serial.print(F("DISH: ")); printSendEnabled(SEND_DISH); printDecodeEnabled(DECODE_DISH); - Serial.print(F("SHARP: ")); printSendEnabled(SEND_SHARP); printDecodeEnabled(DECODE_SHARP); - Serial.print(F("DENON: ")); printSendEnabled(SEND_DENON); printDecodeEnabled(DECODE_DENON); - Serial.print(F("PRONTO: ")); printSendEnabled(SEND_PRONTO); Serial.println(F("(Not Applicable)")); -} - -void printSendEnabled(int flag) { - if (flag) { - Serial.print(F("Enabled ")); - } - else { - Serial.print(F("Disabled ")); - } -} - -void printDecodeEnabled(int flag) { - if (flag) { - Serial.println(F("Enabled")); - } - else { - Serial.println(F("Disabled")); - } -} - -void dumpHeader() { - Serial.println(F("IRremoteInfo - by AnalysIR (http://www.AnalysIR.com/)")); - Serial.println(F(" - A helper sketch to assist in troubleshooting issues with the library by reviewing the settings within the IRremote library")); - Serial.println(F(" - Prints out the important settings within the library, which can be configured to suit the many supported platforms")); - Serial.println(F(" - When seeking on-line support, please post or upload the output of this sketch, where appropriate")); - Serial.println(); - Serial.println(F("IRremote Library Settings")); - Serial.println(F("=========================")); -} - -void dumpFooter() { - Serial.println(); - Serial.println(F("Notes: ")); - Serial.println(F(" - Most of the seetings above can be configured in the following files included as part of the library")); - Serial.println(F(" - IRremteInt.h")); - Serial.println(F(" - IRremote.h")); - Serial.println(F(" - You can save SRAM by disabling the Decode or Send features for any protocol (Near the top of IRremoteInt.h)")); - Serial.println(F(" - Some Timer conflicts, with other libraries, can be easily resolved by configuring a differnt Timer for your platform")); -} diff --git a/lib/Arduino-IRremote/examples/IRsendDemo/IRsendDemo.ino b/lib/Arduino-IRremote/examples/IRsendDemo/IRsendDemo.ino deleted file mode 100644 index 4f23af6c..00000000 --- a/lib/Arduino-IRremote/examples/IRsendDemo/IRsendDemo.ino +++ /dev/null @@ -1,24 +0,0 @@ -/* - * IRremote: IRsendDemo - demonstrates sending IR codes with IRsend - * An IR LED must be connected to Arduino PWM pin 3. - * Version 0.1 July, 2009 - * Copyright 2009 Ken Shirriff - * http://arcfn.com - */ - - -#include - -IRsend irsend; - -void setup() -{ -} - -void loop() { - for (int i = 0; i < 3; i++) { - irsend.sendSony(0xa90, 12); - delay(40); - } - delay(5000); //5 second delay between each signal burst -} diff --git a/lib/Arduino-IRremote/examples/IRsendRawDemo/IRsendRawDemo.ino b/lib/Arduino-IRremote/examples/IRsendRawDemo/IRsendRawDemo.ino deleted file mode 100644 index e83d6e6d..00000000 --- a/lib/Arduino-IRremote/examples/IRsendRawDemo/IRsendRawDemo.ino +++ /dev/null @@ -1,37 +0,0 @@ -/* - * IRremote: IRsendRawDemo - demonstrates sending IR codes with sendRaw - * An IR LED must be connected to Arduino PWM pin 3. - * Version 0.1 July, 2009 - * Copyright 2009 Ken Shirriff - * http://arcfn.com - * - * IRsendRawDemo - added by AnalysIR (via www.AnalysIR.com), 24 August 2015 - * - * This example shows how to send a RAW signal using the IRremote library. - * The example signal is actually a 32 bit NEC signal. - * Remote Control button: LGTV Power On/Off. - * Hex Value: 0x20DF10EF, 32 bits - * - * It is more efficient to use the sendNEC function to send NEC signals. - * Use of sendRaw here, serves only as an example of using the function. - * - */ - - -#include - -IRsend irsend; - -void setup() -{ - -} - -void loop() { - int khz = 38; // 38kHz carrier frequency for the NEC protocol - unsigned int irSignal[] = {9000, 4500, 560, 560, 560, 560, 560, 1690, 560, 560, 560, 560, 560, 560, 560, 560, 560, 560, 560, 1690, 560, 1690, 560, 560, 560, 1690, 560, 1690, 560, 1690, 560, 1690, 560, 1690, 560, 560, 560, 560, 560, 560, 560, 1690, 560, 560, 560, 560, 560, 560, 560, 560, 560, 1690, 560, 1690, 560, 1690, 560, 560, 560, 1690, 560, 1690, 560, 1690, 560, 1690, 560, 39416, 9000, 2210, 560}; //AnalysIR Batch Export (IRremote) - RAW - - irsend.sendRaw(irSignal, sizeof(irSignal) / sizeof(irSignal[0]), khz); //Note the approach used to automatically calculate the size of the array. - - delay(5000); //In this example, the signal will be repeated every 5 seconds, approximately. -} diff --git a/lib/Arduino-IRremote/examples/IRtest/IRtest.ino b/lib/Arduino-IRremote/examples/IRtest/IRtest.ino deleted file mode 100644 index 4845a4a4..00000000 --- a/lib/Arduino-IRremote/examples/IRtest/IRtest.ino +++ /dev/null @@ -1,190 +0,0 @@ -/* - * IRremote: IRtest unittest - * Version 0.1 July, 2009 - * Copyright 2009 Ken Shirriff - * http://arcfn.com - * - * Note: to run these tests, edit IRremote/IRremote.h to add "#define TEST" - * You must then recompile the library by removing IRremote.o and restarting - * the arduino IDE. - */ - -#include -#include - -// Dumps out the decode_results structure. -// Call this after IRrecv::decode() -// void * to work around compiler issue -//void dump(void *v) { -// decode_results *results = (decode_results *)v -void dump(decode_results *results) { - int count = results->rawlen; - if (results->decode_type == UNKNOWN) { - Serial.println("Could not decode message"); - } - else { - if (results->decode_type == NEC) { - Serial.print("Decoded NEC: "); - } - else if (results->decode_type == SONY) { - Serial.print("Decoded SONY: "); - } - else if (results->decode_type == RC5) { - Serial.print("Decoded RC5: "); - } - else if (results->decode_type == RC6) { - Serial.print("Decoded RC6: "); - } - Serial.print(results->value, HEX); - Serial.print(" ("); - Serial.print(results->bits, DEC); - Serial.println(" bits)"); - } - Serial.print("Raw ("); - Serial.print(count, DEC); - Serial.print("): "); - - for (int i = 0; i < count; i++) { - if ((i % 2) == 1) { - Serial.print(results->rawbuf[i]*USECPERTICK, DEC); - } - else { - Serial.print(-(int)results->rawbuf[i]*USECPERTICK, DEC); - } - Serial.print(" "); - } - Serial.println(""); -} - -IRrecv irrecv(0); -decode_results results; - -class IRsendDummy : -public IRsend -{ -public: - // For testing, just log the marks/spaces -#define SENDLOG_LEN 128 - int sendlog[SENDLOG_LEN]; - int sendlogcnt; - IRsendDummy() : - IRsend() { - } - void reset() { - sendlogcnt = 0; - } - void mark(int time) { - sendlog[sendlogcnt] = time; - if (sendlogcnt < SENDLOG_LEN) sendlogcnt++; - } - void space(int time) { - sendlog[sendlogcnt] = -time; - if (sendlogcnt < SENDLOG_LEN) sendlogcnt++; - } - // Copies the dummy buf into the interrupt buf - void useDummyBuf() { - int last = SPACE; - irparams.rcvstate = STATE_STOP; - irparams.rawlen = 1; // Skip the gap - for (int i = 0 ; i < sendlogcnt; i++) { - if (sendlog[i] < 0) { - if (last == MARK) { - // New space - irparams.rawbuf[irparams.rawlen++] = (-sendlog[i] - MARK_EXCESS) / USECPERTICK; - last = SPACE; - } - else { - // More space - irparams.rawbuf[irparams.rawlen - 1] += -sendlog[i] / USECPERTICK; - } - } - else if (sendlog[i] > 0) { - if (last == SPACE) { - // New mark - irparams.rawbuf[irparams.rawlen++] = (sendlog[i] + MARK_EXCESS) / USECPERTICK; - last = MARK; - } - else { - // More mark - irparams.rawbuf[irparams.rawlen - 1] += sendlog[i] / USECPERTICK; - } - } - } - if (irparams.rawlen % 2) { - irparams.rawlen--; // Remove trailing space - } - } -}; - -IRsendDummy irsenddummy; - -void verify(unsigned long val, int bits, int type) { - irsenddummy.useDummyBuf(); - irrecv.decode(&results); - Serial.print("Testing "); - Serial.print(val, HEX); - if (results.value == val && results.bits == bits && results.decode_type == type) { - Serial.println(": OK"); - } - else { - Serial.println(": Error"); - dump(&results); - } -} - -void testNEC(unsigned long val, int bits) { - irsenddummy.reset(); - irsenddummy.sendNEC(val, bits); - verify(val, bits, NEC); -} -void testSony(unsigned long val, int bits) { - irsenddummy.reset(); - irsenddummy.sendSony(val, bits); - verify(val, bits, SONY); -} -void testRC5(unsigned long val, int bits) { - irsenddummy.reset(); - irsenddummy.sendRC5(val, bits); - verify(val, bits, RC5); -} -void testRC6(unsigned long val, int bits) { - irsenddummy.reset(); - irsenddummy.sendRC6(val, bits); - verify(val, bits, RC6); -} - -void test() { - Serial.println("NEC tests"); - testNEC(0x00000000, 32); - testNEC(0xffffffff, 32); - testNEC(0xaaaaaaaa, 32); - testNEC(0x55555555, 32); - testNEC(0x12345678, 32); - Serial.println("Sony tests"); - testSony(0xfff, 12); - testSony(0x000, 12); - testSony(0xaaa, 12); - testSony(0x555, 12); - testSony(0x123, 12); - Serial.println("RC5 tests"); - testRC5(0xfff, 12); - testRC5(0x000, 12); - testRC5(0xaaa, 12); - testRC5(0x555, 12); - testRC5(0x123, 12); - Serial.println("RC6 tests"); - testRC6(0xfffff, 20); - testRC6(0x00000, 20); - testRC6(0xaaaaa, 20); - testRC6(0x55555, 20); - testRC6(0x12345, 20); -} - -void setup() -{ - Serial.begin(9600); - test(); -} - -void loop() { -} diff --git a/lib/Arduino-IRremote/examples/IRtest2/IRtest2.ino b/lib/Arduino-IRremote/examples/IRtest2/IRtest2.ino deleted file mode 100644 index 22a8fa2f..00000000 --- a/lib/Arduino-IRremote/examples/IRtest2/IRtest2.ino +++ /dev/null @@ -1,290 +0,0 @@ -/* - * Test send/receive functions of IRremote, using a pair of Arduinos. - * - * Arduino #1 should have an IR LED connected to the send pin (3). - * Arduino #2 should have an IR detector/demodulator connected to the - * receive pin (11) and a visible LED connected to pin 3. - * - * The cycle: - * Arduino #1 will wait 2 seconds, then run through the tests. - * It repeats this forever. - * Arduino #2 will wait for at least one second of no signal - * (to synchronize with #1). It will then wait for the same test - * signals. It will log all the status to the serial port. It will - * also indicate status through the LED, which will flash each time a test - * is completed. If there is an error, it will light up for 5 seconds. - * - * The test passes if the LED flashes 19 times, pauses, and then repeats. - * The test fails if the LED lights for 5 seconds. - * - * The test software automatically decides which board is the sender and which is - * the receiver by looking for an input on the send pin, which will indicate - * the sender. You should hook the serial port to the receiver for debugging. - * - * Copyright 2010 Ken Shirriff - * http://arcfn.com - */ - -#include - -int RECV_PIN = 11; -int LED_PIN = 3; - -IRrecv irrecv(RECV_PIN); -IRsend irsend; - -decode_results results; - -#define RECEIVER 1 -#define SENDER 2 -#define ERROR 3 - -int mode; - -void setup() -{ - Serial.begin(9600); - // Check RECV_PIN to decide if we're RECEIVER or SENDER - if (digitalRead(RECV_PIN) == HIGH) { - mode = RECEIVER; - irrecv.enableIRIn(); - pinMode(LED_PIN, OUTPUT); - digitalWrite(LED_PIN, LOW); - Serial.println("Receiver mode"); - } - else { - mode = SENDER; - Serial.println("Sender mode"); - } -} - -// Wait for the gap between tests, to synchronize with -// the sender. -// Specifically, wait for a signal followed by a gap of at last gap ms. -void waitForGap(unsigned long gap) { - Serial.println("Waiting for gap"); - while (1) { - while (digitalRead(RECV_PIN) == LOW) { - } - unsigned long time = millis(); - while (digitalRead(RECV_PIN) == HIGH) { - if (millis() - time > gap) { - return; - } - } - } -} - -// Dumps out the decode_results structure. -// Call this after IRrecv::decode() -void dump(decode_results *results) { - int count = results->rawlen; - if (results->decode_type == UNKNOWN) { - Serial.println("Could not decode message"); - } - else { - if (results->decode_type == NEC) { - Serial.print("Decoded NEC: "); - } - else if (results->decode_type == SONY) { - Serial.print("Decoded SONY: "); - } - else if (results->decode_type == RC5) { - Serial.print("Decoded RC5: "); - } - else if (results->decode_type == RC6) { - Serial.print("Decoded RC6: "); - } - Serial.print(results->value, HEX); - Serial.print(" ("); - Serial.print(results->bits, DEC); - Serial.println(" bits)"); - } - Serial.print("Raw ("); - Serial.print(count, DEC); - Serial.print("): "); - - for (int i = 0; i < count; i++) { - if ((i % 2) == 1) { - Serial.print(results->rawbuf[i]*USECPERTICK, DEC); - } - else { - Serial.print(-(int)results->rawbuf[i]*USECPERTICK, DEC); - } - Serial.print(" "); - } - Serial.println(""); -} - - -// Test send or receive. -// If mode is SENDER, send a code of the specified type, value, and bits -// If mode is RECEIVER, receive a code and verify that it is of the -// specified type, value, and bits. For success, the LED is flashed; -// for failure, the mode is set to ERROR. -// The motivation behind this method is that the sender and the receiver -// can do the same test calls, and the mode variable indicates whether -// to send or receive. -void test(const char *label, int type, unsigned long value, int bits) { - if (mode == SENDER) { - Serial.println(label); - if (type == NEC) { - irsend.sendNEC(value, bits); - } - else if (type == SONY) { - irsend.sendSony(value, bits); - } - else if (type == RC5) { - irsend.sendRC5(value, bits); - } - else if (type == RC6) { - irsend.sendRC6(value, bits); - } - else { - Serial.print(label); - Serial.println("Bad type!"); - } - delay(200); - } - else if (mode == RECEIVER) { - irrecv.resume(); // Receive the next value - unsigned long max_time = millis() + 30000; - Serial.print(label); - - // Wait for decode or timeout - while (!irrecv.decode(&results)) { - if (millis() > max_time) { - Serial.println("Timeout receiving data"); - mode = ERROR; - return; - } - } - if (type == results.decode_type && value == results.value && bits == results.bits) { - Serial.println (": OK"); - digitalWrite(LED_PIN, HIGH); - delay(20); - digitalWrite(LED_PIN, LOW); - } - else { - Serial.println(": BAD"); - dump(&results); - mode = ERROR; - } - } -} - -// Test raw send or receive. This is similar to the test method, -// except it send/receives raw data. -void testRaw(const char *label, unsigned int *rawbuf, int rawlen) { - if (mode == SENDER) { - Serial.println(label); - irsend.sendRaw(rawbuf, rawlen, 38 /* kHz */); - delay(200); - } - else if (mode == RECEIVER ) { - irrecv.resume(); // Receive the next value - unsigned long max_time = millis() + 30000; - Serial.print(label); - - // Wait for decode or timeout - while (!irrecv.decode(&results)) { - if (millis() > max_time) { - Serial.println("Timeout receiving data"); - mode = ERROR; - return; - } - } - - // Received length has extra first element for gap - if (rawlen != results.rawlen - 1) { - Serial.print("Bad raw length "); - Serial.println(results.rawlen, DEC); - mode = ERROR; - return; - } - for (int i = 0; i < rawlen; i++) { - long got = results.rawbuf[i+1] * USECPERTICK; - // Adjust for extra duration of marks - if (i % 2 == 0) { - got -= MARK_EXCESS; - } - else { - got += MARK_EXCESS; - } - // See if close enough, within 25% - if (rawbuf[i] * 1.25 < got || got * 1.25 < rawbuf[i]) { - Serial.println(": BAD"); - dump(&results); - mode = ERROR; - return; - } - - } - Serial.println (": OK"); - digitalWrite(LED_PIN, HIGH); - delay(20); - digitalWrite(LED_PIN, LOW); - } -} - -// This is the raw data corresponding to NEC 0x12345678 -unsigned int sendbuf[] = { /* NEC format */ - 9000, 4500, - 560, 560, 560, 560, 560, 560, 560, 1690, /* 1 */ - 560, 560, 560, 560, 560, 1690, 560, 560, /* 2 */ - 560, 560, 560, 560, 560, 1690, 560, 1690, /* 3 */ - 560, 560, 560, 1690, 560, 560, 560, 560, /* 4 */ - 560, 560, 560, 1690, 560, 560, 560, 1690, /* 5 */ - 560, 560, 560, 1690, 560, 1690, 560, 560, /* 6 */ - 560, 560, 560, 1690, 560, 1690, 560, 1690, /* 7 */ - 560, 1690, 560, 560, 560, 560, 560, 560, /* 8 */ - 560}; - -void loop() { - if (mode == SENDER) { - delay(2000); // Delay for more than gap to give receiver a better chance to sync. - } - else if (mode == RECEIVER) { - waitForGap(1000); - } - else if (mode == ERROR) { - // Light up for 5 seconds for error - digitalWrite(LED_PIN, HIGH); - delay(5000); - digitalWrite(LED_PIN, LOW); - mode = RECEIVER; // Try again - return; - } - - // The test suite. - test("SONY1", SONY, 0x123, 12); - test("SONY2", SONY, 0x000, 12); - test("SONY3", SONY, 0xfff, 12); - test("SONY4", SONY, 0x12345, 20); - test("SONY5", SONY, 0x00000, 20); - test("SONY6", SONY, 0xfffff, 20); - test("NEC1", NEC, 0x12345678, 32); - test("NEC2", NEC, 0x00000000, 32); - test("NEC3", NEC, 0xffffffff, 32); - test("NEC4", NEC, REPEAT, 32); - test("RC51", RC5, 0x12345678, 32); - test("RC52", RC5, 0x0, 32); - test("RC53", RC5, 0xffffffff, 32); - test("RC61", RC6, 0x12345678, 32); - test("RC62", RC6, 0x0, 32); - test("RC63", RC6, 0xffffffff, 32); - - // Tests of raw sending and receiving. - // First test sending raw and receiving raw. - // Then test sending raw and receiving decoded NEC - // Then test sending NEC and receiving raw - testRaw("RAW1", sendbuf, 67); - if (mode == SENDER) { - testRaw("RAW2", sendbuf, 67); - test("RAW3", NEC, 0x12345678, 32); - } - else { - test("RAW2", NEC, 0x12345678, 32); - testRaw("RAW3", sendbuf, 67); - } -} diff --git a/lib/Arduino-IRremote/examples/JVCPanasonicSendDemo/JVCPanasonicSendDemo.ino b/lib/Arduino-IRremote/examples/JVCPanasonicSendDemo/JVCPanasonicSendDemo.ino deleted file mode 100644 index 33c167c5..00000000 --- a/lib/Arduino-IRremote/examples/JVCPanasonicSendDemo/JVCPanasonicSendDemo.ino +++ /dev/null @@ -1,29 +0,0 @@ -/* - * IRremote: IRsendDemo - demonstrates sending IR codes with IRsend - * An IR LED must be connected to Arduino PWM pin 3. - * Version 0.1 July, 2009 - * Copyright 2009 Ken Shirriff - * http://arcfn.com - * JVC and Panasonic protocol added by Kristian Lauszus (Thanks to zenwheel and other people at the original blog post) - */ -#include - -#define PanasonicAddress 0x4004 // Panasonic address (Pre data) -#define PanasonicPower 0x100BCBD // Panasonic Power button - -#define JVCPower 0xC5E8 - -IRsend irsend; - -void setup() -{ -} - -void loop() { - irsend.sendPanasonic(PanasonicAddress,PanasonicPower); // This should turn your TV on and off - - irsend.sendJVC(JVCPower, 16,0); // hex value, 16 bits, no repeat - delayMicroseconds(50); // see http://www.sbprojects.com/knowledge/ir/jvc.php for information - irsend.sendJVC(JVCPower, 16,1); // hex value, 16 bits, repeat - delayMicroseconds(50); -} diff --git a/lib/Arduino-IRremote/examples/LGACSendDemo/LGACSendDemo.ino b/lib/Arduino-IRremote/examples/LGACSendDemo/LGACSendDemo.ino deleted file mode 100644 index e3c7dfa3..00000000 --- a/lib/Arduino-IRremote/examples/LGACSendDemo/LGACSendDemo.ino +++ /dev/null @@ -1,263 +0,0 @@ -#include -#include - - -IRsend irsend; -// not used -int RECV_PIN = 11; -IRrecv irrecv (RECV_PIN); - -const int AC_TYPE = 0; -// 0 : TOWER -// 1 : WALL -// - -int AC_HEAT = 0; -// 0 : cooling -// 1 : heating - -int AC_POWER_ON = 0; -// 0 : off -// 1 : on - -int AC_AIR_ACLEAN = 0; -// 0 : off -// 1 : on --> power on - -int AC_TEMPERATURE = 27; -// temperature : 18 ~ 30 - -int AC_FLOW = 1; -// 0 : low -// 1 : mid -// 2 : high -// if AC_TYPE =1, 3 : change -// - - -const int AC_FLOW_TOWER[3] = {0, 4, 6}; -const int AC_FLOW_WALL[4] = {0, 2, 4, 5}; - -unsigned long AC_CODE_TO_SEND; - -int r = LOW; -int o_r = LOW; - -byte a, b; - -void ac_send_code(unsigned long code) -{ - Serial.print("code to send : "); - Serial.print(code, BIN); - Serial.print(" : "); - Serial.println(code, HEX); - - irsend.sendLG(code, 28); -} - -void ac_activate(int temperature, int air_flow) -{ - - int AC_MSBITS1 = 8; - int AC_MSBITS2 = 8; - int AC_MSBITS3 = 0; - int AC_MSBITS4 ; - if ( AC_HEAT == 1 ) { - // heating - AC_MSBITS4 = 4; - } else { - // cooling - AC_MSBITS4 = 0; - } - int AC_MSBITS5 = temperature - 15; - int AC_MSBITS6 ; - - if ( AC_TYPE == 0) { - AC_MSBITS6 = AC_FLOW_TOWER[air_flow]; - } else { - AC_MSBITS6 = AC_FLOW_WALL[air_flow]; - } - - int AC_MSBITS7 = (AC_MSBITS3 + AC_MSBITS4 + AC_MSBITS5 + AC_MSBITS6) & B00001111; - - AC_CODE_TO_SEND = AC_MSBITS1 << 4 ; - AC_CODE_TO_SEND = (AC_CODE_TO_SEND + AC_MSBITS2) << 4; - AC_CODE_TO_SEND = (AC_CODE_TO_SEND + AC_MSBITS3) << 4; - AC_CODE_TO_SEND = (AC_CODE_TO_SEND + AC_MSBITS4) << 4; - AC_CODE_TO_SEND = (AC_CODE_TO_SEND + AC_MSBITS5) << 4; - AC_CODE_TO_SEND = (AC_CODE_TO_SEND + AC_MSBITS6) << 4; - AC_CODE_TO_SEND = (AC_CODE_TO_SEND + AC_MSBITS7); - - ac_send_code(AC_CODE_TO_SEND); - - AC_POWER_ON = 1; - AC_TEMPERATURE = temperature; - AC_FLOW = air_flow; -} - -void ac_change_air_swing(int air_swing) -{ - if ( AC_TYPE == 0) { - if ( air_swing == 1) { - AC_CODE_TO_SEND = 0x881316B; - } else { - AC_CODE_TO_SEND = 0x881317C; - } - } else { - if ( air_swing == 1) { - AC_CODE_TO_SEND = 0x8813149; - } else { - AC_CODE_TO_SEND = 0x881315A; - } - } - - ac_send_code(AC_CODE_TO_SEND); -} - -void ac_power_down() -{ - AC_CODE_TO_SEND = 0x88C0051; - - ac_send_code(AC_CODE_TO_SEND); - - AC_POWER_ON = 0; -} - -void ac_air_clean(int air_clean) -{ - if ( air_clean == 1) { - AC_CODE_TO_SEND = 0x88C000C; - } else { - AC_CODE_TO_SEND = 0x88C0084; - } - - ac_send_code(AC_CODE_TO_SEND); - - AC_AIR_ACLEAN = air_clean; -} - -void setup() -{ - Serial.begin(38400); - delay(1000); - Wire.begin(7); - Wire.onReceive(receiveEvent); - - Serial.println(" - - - T E S T - - - "); - - /* test - ac_activate(25, 1); - delay(5000); - ac_activate(27, 2); - delay(5000); - - */ -} - -void loop() -{ - - - ac_activate(25, 1); - delay(5000); - ac_activate(27, 0); - delay(5000); - - - if ( r != o_r) { - - /* - # a : mode or temp b : air_flow, temp, swing, clean, cooling/heating - # 18 ~ 30 : temp 0 ~ 2 : flow // on - # 0 : off 0 - # 1 : on 0 - # 2 : air_swing 0 or 1 - # 3 : air_clean 0 or 1 - # 4 : air_flow 0 ~ 2 : flow - # 5 : temp 18 ~ 30 - # + : temp + 1 - # - : temp - 1 - # m : change cooling to air clean, air clean to cooling - */ - Serial.print("a : "); - Serial.print(a); - Serial.print(" b : "); - Serial.println(b); - - switch (a) { - case 0: // off - ac_power_down(); - break; - case 1: // on - ac_activate(AC_TEMPERATURE, AC_FLOW); - break; - case 2: - if ( b == 0 || b == 1 ) { - ac_change_air_swing(b); - } - break; - case 3: // 1 : clean on, power on - if ( b == 0 || b == 1 ) { - ac_air_clean(b); - } - break; - case 4: - if ( 0 <= b && b <= 2 ) { - ac_activate(AC_TEMPERATURE, b); - } - break; - case 5: - if (18 <= b && b <= 30 ) { - ac_activate(b, AC_FLOW); - } - break; - case '+': - if ( 18 <= AC_TEMPERATURE && AC_TEMPERATURE <= 29 ) { - ac_activate((AC_TEMPERATURE + 1), AC_FLOW); - } - break; - case '-': - if ( 19 <= AC_TEMPERATURE && AC_TEMPERATURE <= 30 ) { - ac_activate((AC_TEMPERATURE - 1), AC_FLOW); - } - break; - case 'm': - /* - if ac is on, 1) turn off, 2) turn on ac_air_clean(1) - if ac is off, 1) turn on, 2) turn off ac_air_clean(0) - */ - if ( AC_POWER_ON == 1 ) { - ac_power_down(); - delay(100); - ac_air_clean(1); - } else { - if ( AC_AIR_ACLEAN == 1) { - ac_air_clean(0); - delay(100); - } - ac_activate(AC_TEMPERATURE, AC_FLOW); - } - break; - default: - if ( 18 <= a && a <= 30 ) { - if ( 0 <= b && b <= 2 ) { - ac_activate(a, b); - } - } - } - - o_r = r ; - } - delay(100); -} - - - -void receiveEvent(int howMany) -{ - a = Wire.read(); - b = Wire.read(); - r = !r ; -} - - diff --git a/lib/Arduino-IRremote/examples/LGACSendDemo/LGACSendDemo.md b/lib/Arduino-IRremote/examples/LGACSendDemo/LGACSendDemo.md deleted file mode 100644 index 62c70731..00000000 --- a/lib/Arduino-IRremote/examples/LGACSendDemo/LGACSendDemo.md +++ /dev/null @@ -1,93 +0,0 @@ -=== decoding for LG A/C ==== -- 1) remote of LG AC has two type of HDR mark/space, 8000/4000 and 3100/10000 -- 2) HDR 8000/4000 is decoded using decodeLG(IRrecvDumpV2) without problem -- 3) for HDR 3100/10000, use AnalysIR's code : http://www.analysir.com/blog/2014/03/19/air-conditioners-problems-recording-long-infrared-remote-control-signals-arduino/ -- 4) for bin output based on AnalysIR's code : https://gist.github.com/chaeplin/a3a4b4b6b887c663bfe8 -- 5) remove first two byte(11) -- 6) sample rawcode with bin output : https://gist.github.com/chaeplin/134d232e0b8cfb898860 - - -=== *** === -- 1) Sample raw code : https://gist.github.com/chaeplin/ab2a7ad1533c41260f0d -- 2) send raw code : https://gist.github.com/chaeplin/7c800d3166463bb51be4 - - -=== *** === -- (0) : Cooling or Heating -- (1) : fixed -- (2) : fixed -- (3) : special(power, swing, air clean) -- (4) : change air flow, temperature, cooling(0)/heating(4) -- (5) : temperature ( 15 + (5) = ) -- (6) : air flow -- (7) : crc ( 3 + 4 + 5 + 6 ) & B00001111 - - -°F = °C × 1.8 + 32 -°C = (°F − 32) / 1.8 - - -=== *** === -* remote / Korea / without heating - -| status |(0)| (1)| (2)| (3)| (4)| (5)| (6)| (7) -|----------------|---|----|----|----|----|----|----|---- -| on / 25 / mid | C |1000|1000|0000|0000|1010|0010|1100 -| on / 26 / mid | C |1000|1000|0000|0000|1011|0010|1101 -| on / 27 / mid | C |1000|1000|0000|0000|1100|0010|1110 -| on / 28 / mid | C |1000|1000|0000|0000|1101|0010|1111 -| on / 25 / high | C |1000|1000|0000|0000|1010|0100|1110 -| on / 26 / high | C |1000|1000|0000|0000|1011|0100|1111 -| on / 27 / high | C |1000|1000|0000|0000|1100|0100|0000 -| on / 28 / high | C |1000|1000|0000|0000|1101|0100|0001 -|----------------|---|----|----|----|----|----|----|---- -| 1 up | C |1000|1000|0000|1000|1101|0100|1001 -|----------------|---|----|----|----|----|----|----|---- -| Cool power | C |1000|1000|0001|0000|0000|1100|1101 -| energy saving | C |1000|1000|0001|0000|0000|0100|0101 -| power | C |1000|1000|0001|0000|0000|1000|1001 -| flow/up/down | C |1000|1000|0001|0011|0001|0100|1001 -| up/down off | C |1000|1000|0001|0011|0001|0101|1010 -| flow/left/right| C |1000|1000|0001|0011|0001|0110|1011 -| left/right off | C |1000|1000|0001|0011|0001|0111|1100 -|----------------|---|----|----|----|----|----|----|---- -| Air clean | C |1000|1000|1100|0000|0000|0000|1100 -|----------------|---|----|----|----|----|----|----|---- -| off | C |1000|1000|1100|0000|0000|0101|0001 - - - -* remote / with heating -* converted using raw code at https://github.com/chaeplin/RaspAC/blob/master/lircd.conf - -| status |(0)| (1)| (2)| (3)| (4)| (5)| (6)| (7) -|----------------|---|----|----|----|----|----|----|---- -| on | C |1000|1000|0000|0000|1011|0010|1101 -|----------------|---|----|----|----|----|----|----|---- -| off | C |1000|1000|1100|0000|0000|0101|0001 -|----------------|---|----|----|----|----|----|----|---- -| 64 / 18 | C |1000|1000|0000|0000|0011|0100|0111 -| 66 / 19 | C |1000|1000|0000|0000|0100|0100|1000 -| 68 / 20 | C |1000|1000|0000|0000|0101|0100|1001 -| 70 / 21 | C |1000|1000|0000|0000|0110|0100|1010 -| 72 / 22 | C |1000|1000|0000|0000|0111|0100|1011 -| 74 / 23 | C |1000|1000|0000|0000|1000|0100|1100 -| 76 / 25 | C |1000|1000|0000|0000|1010|0100|1110 -| 78 / 26 | C |1000|1000|0000|0000|1011|0100|1111 -| 80 / 27 | C |1000|1000|0000|0000|1100|0100|0000 -| 82 / 28 | C |1000|1000|0000|0000|1101|0100|0001 -| 84 / 29 | C |1000|1000|0000|0000|1110|0100|0010 -| 86 / 30 | C |1000|1000|0000|0000|1111|0100|0011 -|----------------|---|----|----|----|----|----|----|---- -| heat64 | H |1000|1000|0000|0100|0011|0100|1011 -| heat66 | H |1000|1000|0000|0100|0100|0100|1100 -| heat68 | H |1000|1000|0000|0100|0101|0100|1101 -| heat70 | H |1000|1000|0000|0100|0110|0100|1110 -| heat72 | H |1000|1000|0000|0100|0111|0100|1111 -| heat74 | H |1000|1000|0000|0100|1000|0100|0000 -| heat76 | H |1000|1000|0000|0100|1001|0100|0001 -| heat78 | H |1000|1000|0000|0100|1011|0100|0011 -| heat80 | H |1000|1000|0000|0100|1100|0100|0100 -| heat82 | H |1000|1000|0000|0100|1101|0100|0101 -| heat84 | H |1000|1000|0000|0100|1110|0100|0110 -| heat86 | H |1000|1000|0000|0100|1111|0100|0111 diff --git a/lib/Arduino-IRremote/examples/LegoPowerFunctionsSendDemo/LegoPowerFunctionsSendDemo.ino b/lib/Arduino-IRremote/examples/LegoPowerFunctionsSendDemo/LegoPowerFunctionsSendDemo.ino deleted file mode 100644 index e43d06c2..00000000 --- a/lib/Arduino-IRremote/examples/LegoPowerFunctionsSendDemo/LegoPowerFunctionsSendDemo.ino +++ /dev/null @@ -1,22 +0,0 @@ -/* - * LegoPowerFunctionsSendDemo: LEGO Power Functions - * Copyright (c) 2016 Philipp Henkel - */ - -#include -#include - -IRsend irsend; - -void setup() { -} - -void loop() { - // Send repeated command "channel 1, blue forward, red backward" - irsend.sendLegoPowerFunctions(0x197); - delay(2000); - - // Send single command "channel 1, blue forward, red backward" - irsend.sendLegoPowerFunctions(0x197, false); - delay(2000); -} diff --git a/lib/Arduino-IRremote/examples/LegoPowerFunctionsTests/LegoPowerFunctionsTests.ino b/lib/Arduino-IRremote/examples/LegoPowerFunctionsTests/LegoPowerFunctionsTests.ino deleted file mode 100644 index 65760e2f..00000000 --- a/lib/Arduino-IRremote/examples/LegoPowerFunctionsTests/LegoPowerFunctionsTests.ino +++ /dev/null @@ -1,193 +0,0 @@ -/* - * LegoPowerFunctionsTest: LEGO Power Functions Tests - * Copyright (c) 2016, 2017 Philipp Henkel - */ - -#include - -void setup() { - Serial.begin(9600); - delay(1000); // wait for reset triggered by serial connection - runBitStreamEncoderTests(); -} - -void loop() { -} - -void runBitStreamEncoderTests() { - Serial.println(); - Serial.println("BitStreamEncoder Tests"); - static LegoPfBitStreamEncoder bitStreamEncoder; - testStartBit(bitStreamEncoder); - testLowBit(bitStreamEncoder); - testHighBit(bitStreamEncoder); - testMessageBitCount(bitStreamEncoder); - testMessageBitCountRepeat(bitStreamEncoder); - testMessage407(bitStreamEncoder); - testMessage407Repeated(bitStreamEncoder); - testGetChannelId1(bitStreamEncoder); - testGetChannelId2(bitStreamEncoder); - testGetChannelId3(bitStreamEncoder); - testGetChannelId4(bitStreamEncoder); - testGetMessageLengthAllHigh(bitStreamEncoder); - testGetMessageLengthAllLow(bitStreamEncoder); -} - -void logTestResult(bool testPassed) { - if (testPassed) { - Serial.println("OK"); - } - else { - Serial.println("FAIL ############"); - } -} - -void testStartBit(LegoPfBitStreamEncoder& bitStreamEncoder) { - Serial.print(" testStartBit "); - bitStreamEncoder.reset(0, false); - int startMark = bitStreamEncoder.getMarkDuration(); - int startPause = bitStreamEncoder.getPauseDuration(); - logTestResult(startMark == 158 && startPause == 1184-158); -} - -void testLowBit(LegoPfBitStreamEncoder& bitStreamEncoder) { - Serial.print(" testLowBit "); - bitStreamEncoder.reset(0, false); - bitStreamEncoder.next(); - int lowMark = bitStreamEncoder.getMarkDuration(); - int lowPause = bitStreamEncoder.getPauseDuration(); - logTestResult(lowMark == 158 && lowPause == 421-158); -} - -void testHighBit(LegoPfBitStreamEncoder& bitStreamEncoder) { - Serial.print(" testHighBit "); - bitStreamEncoder.reset(0xFFFF, false); - bitStreamEncoder.next(); - int highMark = bitStreamEncoder.getMarkDuration(); - int highPause = bitStreamEncoder.getPauseDuration(); - logTestResult(highMark == 158 && highPause == 711-158); -} - -void testMessageBitCount(LegoPfBitStreamEncoder& bitStreamEncoder) { - Serial.print(" testMessageBitCount "); - bitStreamEncoder.reset(0xFFFF, false); - int bitCount = 1; - while (bitStreamEncoder.next()) { - bitCount++; - } - logTestResult(bitCount == 18); -} - -boolean check(LegoPfBitStreamEncoder& bitStreamEncoder, unsigned long markDuration, unsigned long pauseDuration) { - bool result = true; - result = result && bitStreamEncoder.getMarkDuration() == markDuration; - result = result && bitStreamEncoder.getPauseDuration() == pauseDuration; - return result; -} - -boolean checkNext(LegoPfBitStreamEncoder& bitStreamEncoder, unsigned long markDuration, unsigned long pauseDuration) { - bool result = bitStreamEncoder.next(); - result = result && check(bitStreamEncoder, markDuration, pauseDuration); - return result; -} - -boolean checkDataBitsOfMessage407(LegoPfBitStreamEncoder& bitStreamEncoder) { - bool result = true; - result = result && checkNext(bitStreamEncoder, 158, 263); - result = result && checkNext(bitStreamEncoder, 158, 263); - result = result && checkNext(bitStreamEncoder, 158, 263); - result = result && checkNext(bitStreamEncoder, 158, 263); - result = result && checkNext(bitStreamEncoder, 158, 263); - result = result && checkNext(bitStreamEncoder, 158, 263); - result = result && checkNext(bitStreamEncoder, 158, 263); - result = result && checkNext(bitStreamEncoder, 158, 553); - result = result && checkNext(bitStreamEncoder, 158, 553); - result = result && checkNext(bitStreamEncoder, 158, 263); - result = result && checkNext(bitStreamEncoder, 158, 263); - result = result && checkNext(bitStreamEncoder, 158, 553); - result = result && checkNext(bitStreamEncoder, 158, 263); - result = result && checkNext(bitStreamEncoder, 158, 553); - result = result && checkNext(bitStreamEncoder, 158, 553); - result = result && checkNext(bitStreamEncoder, 158, 553); - return result; -} - -void testMessage407(LegoPfBitStreamEncoder& bitStreamEncoder) { - Serial.print(" testMessage407 "); - bitStreamEncoder.reset(407, false); - bool result = true; - result = result && check(bitStreamEncoder, 158, 1026); - result = result && checkDataBitsOfMessage407(bitStreamEncoder); - result = result && checkNext(bitStreamEncoder, 158, 1026); - result = result && !bitStreamEncoder.next(); - logTestResult(result); -} - -void testMessage407Repeated(LegoPfBitStreamEncoder& bitStreamEncoder) { - Serial.print(" testMessage407Repeated "); - bitStreamEncoder.reset(407, true); - bool result = true; - result = result && check(bitStreamEncoder, 158, 1026); - result = result && checkDataBitsOfMessage407(bitStreamEncoder); - result = result && checkNext(bitStreamEncoder, 158, 1026L + 5L * 16000L - 10844L); - result = result && checkNext(bitStreamEncoder, 158, 1026); - result = result && checkDataBitsOfMessage407(bitStreamEncoder); - result = result && checkNext(bitStreamEncoder, 158, 1026L + 5L * 16000L - 10844L); - result = result && checkNext(bitStreamEncoder, 158, 1026); - result = result && checkDataBitsOfMessage407(bitStreamEncoder); - result = result && checkNext(bitStreamEncoder, 158, 1026L + 8L * 16000L - 10844L); - result = result && checkNext(bitStreamEncoder, 158, 1026); - result = result && checkDataBitsOfMessage407(bitStreamEncoder); - result = result && checkNext(bitStreamEncoder, 158, 1026L + 8L * 16000L - 10844L); - result = result && checkNext(bitStreamEncoder, 158, 1026); - result = result && checkDataBitsOfMessage407(bitStreamEncoder); - result = result && checkNext(bitStreamEncoder, 158, 1026); - result = result && !bitStreamEncoder.next(); - logTestResult(result); -} - -void testMessageBitCountRepeat(LegoPfBitStreamEncoder& bitStreamEncoder) { - Serial.print(" testMessageBitCountRepeat "); - bitStreamEncoder.reset(0xFFFF, true); - int bitCount = 1; - while (bitStreamEncoder.next()) { - bitCount++; - } - logTestResult(bitCount == 5*18); -} - -void testGetChannelId1(LegoPfBitStreamEncoder& bitStreamEncoder) { - Serial.print(" testGetChannelId1 "); - bitStreamEncoder.reset(407, false); - logTestResult(bitStreamEncoder.getChannelId() == 1); -} - -void testGetChannelId2(LegoPfBitStreamEncoder& bitStreamEncoder) { - Serial.print(" testGetChannelId2 "); - bitStreamEncoder.reset(4502, false); - logTestResult(bitStreamEncoder.getChannelId() == 2); -} - -void testGetChannelId3(LegoPfBitStreamEncoder& bitStreamEncoder) { - Serial.print(" testGetChannelId3 "); - bitStreamEncoder.reset(8597, false); - logTestResult(bitStreamEncoder.getChannelId() == 3); -} - -void testGetChannelId4(LegoPfBitStreamEncoder& bitStreamEncoder) { - Serial.print(" testGetChannelId4 "); - bitStreamEncoder.reset(12692, false); - logTestResult(bitStreamEncoder.getChannelId() == 4); -} - -void testGetMessageLengthAllHigh(LegoPfBitStreamEncoder& bitStreamEncoder) { - Serial.print(" testGetMessageLengthAllHigh "); - bitStreamEncoder.reset(0xFFFF, false); - logTestResult(bitStreamEncoder.getMessageLength() == 13744); -} - -void testGetMessageLengthAllLow(LegoPfBitStreamEncoder& bitStreamEncoder) { - Serial.print(" testGetMessageLengthAllLow "); - bitStreamEncoder.reset(0x0, false); - logTestResult(bitStreamEncoder.getMessageLength() == 9104); -} diff --git a/lib/Arduino-IRremote/irPronto.cpp b/lib/Arduino-IRremote/irPronto.cpp deleted file mode 100644 index 49d2685f..00000000 --- a/lib/Arduino-IRremote/irPronto.cpp +++ /dev/null @@ -1,513 +0,0 @@ -#define TEST 0 - -#if TEST -# define SEND_PRONTO 1 -# define PRONTO_ONCE false -# define PRONTO_REPEAT true -# define PRONTO_FALLBACK true -# define PRONTO_NOFALLBACK false -#endif - -#if SEND_PRONTO - -//****************************************************************************** -#if TEST -# include - void enableIROut (int freq) { printf("\nFreq = %d KHz\n", freq); } - void mark (int t) { printf("+%d," , t); } - void space (int t) { printf("-%d, ", t); } -#else -# include "IRremote.h" -#endif // TEST - -//+============================================================================= -// Check for a valid hex digit -// -bool ishex (char ch) -{ - return ( ((ch >= '0') && (ch <= '9')) || - ((ch >= 'A') && (ch <= 'F')) || - ((ch >= 'a') && (ch <= 'f')) ) ? true : false ; -} - -//+============================================================================= -// Check for a valid "blank" ... '\0' is a valid "blank" -// -bool isblank (char ch) -{ - return ((ch == ' ') || (ch == '\t') || (ch == '\0')) ? true : false ; -} - -//+============================================================================= -// Bypass spaces -// -bool byp (char** pcp) -{ - while (isblank(**pcp)) (*pcp)++ ; -} - -//+============================================================================= -// Hex-to-Byte : Decode a hex digit -// We assume the character has already been validated -// -uint8_t htob (char ch) -{ - if ((ch >= '0') && (ch <= '9')) return ch - '0' ; - if ((ch >= 'A') && (ch <= 'F')) return ch - 'A' + 10 ; - if ((ch >= 'a') && (ch <= 'f')) return ch - 'a' + 10 ; -} - -//+============================================================================= -// Hex-to-Word : Decode a block of 4 hex digits -// We assume the string has already been validated -// and the pointer being passed points at the start of a block of 4 hex digits -// -uint16_t htow (char* cp) -{ - return ( (htob(cp[0]) << 12) | (htob(cp[1]) << 8) | - (htob(cp[2]) << 4) | (htob(cp[3]) ) ) ; -} - -//+============================================================================= -// -bool sendPronto (char* s, bool repeat, bool fallback) -{ - int i; - int len; - int skip; - char* cp; - uint16_t freq; // Frequency in KHz - uint8_t usec; // pronto uSec/tick - uint8_t once; - uint8_t rpt; - - // Validate the string - for (cp = s; *cp; cp += 4) { - byp(&cp); - if ( !ishex(cp[0]) || !ishex(cp[1]) || - !ishex(cp[2]) || !ishex(cp[3]) || !isblank(cp[4]) ) return false ; - } - - // We will use cp to traverse the string - cp = s; - - // Check mode = Oscillated/Learned - byp(&cp); - if (htow(cp) != 0000) return false; - cp += 4; - - // Extract & set frequency - byp(&cp); - freq = (int)(1000000 / (htow(cp) * 0.241246)); // Rounding errors will occur, tolerance is +/- 10% - usec = (int)(((1.0 / freq) * 1000000) + 0.5); // Another rounding error, thank Cod for analogue electronics - freq /= 1000; // This will introduce a(nother) rounding error which we do not want in the usec calcualtion - cp += 4; - - // Get length of "once" code - byp(&cp); - once = htow(cp); - cp += 4; - - // Get length of "repeat" code - byp(&cp); - rpt = htow(cp); - cp += 4; - - // Which code are we sending? - if (fallback) { // fallback on the "other" code if "this" code is not present - if (!repeat) { // requested 'once' - if (once) len = once * 2, skip = 0 ; // if once exists send it - else len = rpt * 2, skip = 0 ; // else send repeat code - } else { // requested 'repeat' - if (rpt) len = rpt * 2, skip = 0 ; // if rpt exists send it - else len = once * 2, skip = 0 ; // else send once code - } - } else { // Send what we asked for, do not fallback if the code is empty! - if (!repeat) len = once * 2, skip = 0 ; // 'once' starts at 0 - else len = rpt * 2, skip = once ; // 'repeat' starts where 'once' ends - } - - // Skip to start of code - for (i = 0; i < skip; i++, cp += 4) byp(&cp) ; - - // Send code - enableIROut(freq); - for (i = 0; i < len; i++) { - byp(&cp); - if (i & 1) space(htow(cp) * usec); - else mark (htow(cp) * usec); - cp += 4; - } -} - -//+============================================================================= -#if TEST - -int main ( ) -{ - char prontoTest[] = - "0000 0070 0000 0032 0080 0040 0010 0010 0010 0030 " // 10 - "0010 0010 0010 0010 0010 0010 0010 0010 0010 0010 " // 20 - "0010 0010 0010 0010 0010 0010 0010 0010 0010 0010 " // 30 - "0010 0010 0010 0030 0010 0010 0010 0010 0010 0010 " // 40 - "0010 0010 0010 0010 0010 0010 0010 0010 0010 0010 " // 50 - "0010 0010 0010 0030 0010 0010 0010 0010 0010 0010 " // 60 - "0010 0010 0010 0010 0010 0010 0010 0010 0010 0010 " // 70 - "0010 0010 0010 0030 0010 0010 0010 0030 0010 0010 " // 80 - "0010 0010 0010 0030 0010 0010 0010 0010 0010 0030 " // 90 - "0010 0010 0010 0030 0010 0010 0010 0010 0010 0030 " // 100 - "0010 0030 0010 0aa6"; // 104 - - sendPronto(prontoTest, PRONTO_ONCE, PRONTO_FALLBACK); // once code - sendPronto(prontoTest, PRONTO_REPEAT, PRONTO_FALLBACK); // repeat code - sendPronto(prontoTest, PRONTO_ONCE, PRONTO_NOFALLBACK); // once code - sendPronto(prontoTest, PRONTO_REPEAT, PRONTO_NOFALLBACK); // repeat code - - return 0; -} - -#endif // TEST - -#endif // SEND_PRONTO - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -#if 0 -//****************************************************************************** -// Sources: -// http://www.remotecentral.com/features/irdisp2.htm -// http://www.hifi-remote.com/wiki/index.php?title=Working_With_Pronto_Hex -//****************************************************************************** - -#include -#include - -#define IRPRONTO -#include "IRremoteInt.h" // The Arduino IRremote library defines USECPERTICK - -//------------------------------------------------------------------------------ -// Source: https://www.google.co.uk/search?q=DENON+MASTER+IR+Hex+Command+Sheet -// -> http://assets.denon.com/documentmaster/us/denon%20master%20ir%20hex.xls -// -char prontoTest[] = - "0000 0070 0000 0032 0080 0040 0010 0010 0010 0030 " // 10 - "0010 0010 0010 0010 0010 0010 0010 0010 0010 0010 " // 20 - "0010 0010 0010 0010 0010 0010 0010 0010 0010 0010 " // 30 - "0010 0010 0010 0030 0010 0010 0010 0010 0010 0010 " // 40 - "0010 0010 0010 0010 0010 0010 0010 0010 0010 0010 " // 50 - "0010 0010 0010 0030 0010 0010 0010 0010 0010 0010 " // 60 - "0010 0010 0010 0010 0010 0010 0010 0010 0010 0010 " // 70 - "0010 0010 0010 0030 0010 0010 0010 0030 0010 0010 " // 80 - "0010 0010 0010 0030 0010 0010 0010 0010 0010 0030 " // 90 - "0010 0010 0010 0030 0010 0010 0010 0010 0010 0030 " // 100 - "0010 0030 0010 0aa6"; // 104 - -//------------------------------------------------------------------------------ -// This is the longest code we can support -#define CODEMAX 200 - -//------------------------------------------------------------------------------ -// This is the data we pull out of the pronto code -typedef - struct { - int freq; // Carrier frequency (in Hz) - int usec; // uSec per tick (based on freq) - - int codeLen; // Length of code - uint16_t code[CODEMAX]; // Code in hex - - int onceLen; // Length of "once" transmit - uint16_t* once; // Pointer to start within 'code' - - int rptLen; // Length of "repeat" transmit - uint16_t* rpt; // Pointer to start within 'code' - } -pronto_t; - -//------------------------------------------------------------------------------ -// From what I have seen, the only time we go over 8-bits is the 'space' -// on the end which creates the lead-out/inter-code gap. Assuming I'm right, -// we can code this up as a special case and otherwise halve the size of our -// data! -// Ignoring the first four values (the config data) and the last value -// (the lead-out), if you find a protocol that uses values greater than 00fe -// we are going to have to revisit this code! -// -// -// So, the 0th byte will be the carrier frequency in Khz (NOT Hz) -// " 1st " " " " length of the "once" code -// " 2nd " " " " length of the "repeat" code -// -// Thereafter, odd bytes will be Mark lengths as a multiple of USECPERTICK uS -// even " " " Space " " " " " " " -// -// Any occurence of "FF" in either a Mark or a Space will indicate -// "Use the 16-bit FF value" which will also be a multiple of USECPERTICK uS -// -// -// As a point of comparison, the test code (prontoTest[]) is 520 bytes -// (yes, more than 0.5KB of our Arduino's precious 32KB) ... after conversion -// to pronto hex that goes down to ((520/5)*2) = 208 bytes ... once converted to -// our format we are down to ((208/2) -1 -1 +2) = 104 bytes -// -// In fariness this is still very memory-hungry -// ...As a rough guide: -// 10 codes cost 1K of memory (this will vary depending on the protocol). -// -// So if you're building a complex remote control, you will probably need to -// keep the codes on an external memory device (not in the Arduino sketch) and -// load them as you need them. Hmmm. -// -// This dictates that "Oscillated Pronto Codes" are probably NOT the way forward -// -// For example, prontoTest[] happens to be: A 48-bit IR code in Denon format -// So we know it starts with 80/40 (Denon header) -// and ends with 10/aa6 (Denon leadout) -// and all (48) bits in between are either 10/10 (Denon 0) -// or 10/30 (Denon 1) -// So we could easily store this data in 1-byte ("Denon") -// + 1-byte (Length=48) -// + 6-bytes (IR code) -// At 8-bytes per code, we can store 128 codes in 1KB or memory - that's a lot -// better than the 2 (two) we started off with! -// -// And serendipitously, by reducing the amount of data, our program will run -// a LOT faster! -// -// Again, I repeat, even after you have spent time converting the "Oscillated -// Pronto Codes" in to IRremote format, it will be a LOT more memory-hungry -// than using sendDenon() (or whichever) ...BUT these codes are easily -// available on the internet, so we'll support them! -// -typedef - struct { - uint16_t FF; - uint8_t code[CODEMAX]; - } -irCode_t; - -//------------------------------------------------------------------------------ -#define DEBUGF(...) printf(__VA_ARGS__) - -//+============================================================================= -// String must be block of 4 hex digits separated with blanks -// -bool validate (char* cp, int* len) -{ - for (*len = 0; *cp; (*len)++, cp += 4) { - byp(&cp); - if ( !ishex(cp[0]) || !ishex(cp[1]) || - !ishex(cp[2]) || !ishex(cp[3]) || !isblank(cp[4]) ) return false ; - } - - return true; -} - -//+============================================================================= -// Hex-to-Byte : Decode a hex digit -// We assume the character has already been validated -// -uint8_t htob (char ch) -{ - if ((ch >= '0') && (ch <= '9')) return ch - '0' ; - if ((ch >= 'A') && (ch <= 'F')) return ch - 'A' + 10 ; - if ((ch >= 'a') && (ch <= 'f')) return ch - 'a' + 10 ; -} - -//+============================================================================= -// Hex-to-Word : Decode a block of 4 hex digits -// We assume the string has already been validated -// and the pointer being passed points at the start of a block of 4 hex digits -// -uint16_t htow (char* cp) -{ - return ( (htob(cp[0]) << 12) | (htob(cp[1]) << 8) | - (htob(cp[2]) << 4) | (htob(cp[3]) ) ) ; -} - -//+============================================================================= -// Convert the pronto string in to data -// -bool decode (char* s, pronto_t* p, irCode_t* ir) -{ - int i, len; - char* cp; - - // Validate the Pronto string - if (!validate(s, &p->codeLen)) { - DEBUGF("Invalid pronto string\n"); - return false ; - } - DEBUGF("Found %d hex codes\n", p->codeLen); - - // Allocate memory to store the decoded string - //if (!(p->code = malloc(p->len))) { - // DEBUGF("Memory allocation failed\n"); - // return false ; - //} - - // Check in case our code is too long - if (p->codeLen > CODEMAX) { - DEBUGF("Code too long, edit CODEMAX and recompile\n"); - return false ; - } - - // Decode the string - cp = s; - for (i = 0; i < p->codeLen; i++, cp += 4) { - byp(&cp); - p->code[i] = htow(cp); - } - - // Announce our findings - DEBUGF("Input: |%s|\n", s); - DEBUGF("Found: |"); - for (i = 0; i < p->codeLen; i++) DEBUGF("%04x ", p->code[i]) ; - DEBUGF("|\n"); - - DEBUGF("Form [%04X] : ", p->code[0]); - if (p->code[0] == 0x0000) DEBUGF("Oscillated (Learned)\n"); - else if (p->code[0] == 0x0100) DEBUGF("Unmodulated\n"); - else DEBUGF("Unknown\n"); - if (p->code[0] != 0x0000) return false ; // Can only handle Oscillated - - // Calculate the carrier frequency (+/- 10%) & uSecs per pulse - // Pronto uses a crystal which generates a timeabse of 0.241246 - p->freq = (int)(1000000 / (p->code[1] * 0.241246)); - p->usec = (int)(((1.0 / p->freq) * 1000000) + 0.5); - ir->code[0] = p->freq / 1000; - DEBUGF("Freq [%04X] : %d Hz (%d uS/pluse) -> %d KHz\n", - p->code[1], p->freq, p->usec, ir->code[0]); - - // Set the length & start pointer for the "once" code - p->onceLen = p->code[2]; - p->once = &p->code[4]; - ir->code[1] = p->onceLen; - DEBUGF("Once [%04X] : %d\n", p->code[2], p->onceLen); - - // Set the length & start pointer for the "repeat" code - p->rptLen = p->code[3]; - p->rpt = &p->code[4 + p->onceLen]; - ir->code[2] = p->rptLen; - DEBUGF("Rpt [%04X] : %d\n", p->code[3], p->rptLen); - - // Check everything tallies - if (1 + 1 + 1 + 1 + (p->onceLen * 2) + (p->rptLen * 2) != p->codeLen) { - DEBUGF("Bad code length\n"); - return false; - } - - // Convert the IR data to our new format - ir->FF = p->code[p->codeLen - 1]; - - len = (p->onceLen * 2) + (p->rptLen * 2); - DEBUGF("Encoded: |"); - for (i = 0; i < len; i++) { - if (p->code[i+4] == ir->FF) { - ir->code[i+3] = 0xFF; - } else if (p->code[i+4] > 0xFE) { - DEBUGF("\n%04X : Mark/Space overflow\n", p->code[i+4]); - return false; - } else { - ir->code[i+3] = (p->code[i+4] * p->usec) / USECPERTICK; - } - DEBUGF("%s%d", !i ? "" : (i&1 ? "," : ", "), ir->code[i+3]); - } - DEBUGF("|\n"); - - ir->FF = (ir->FF * p->usec) / USECPERTICK; - DEBUGF("FF -> %d\n", ir->FF); - - return true; -} - -//+============================================================================= -// -void irDump (irCode_t* ir) -{ - int i, len; - - printf("uint8_t buttonName[%d] = {", len); - - printf("%d,%d, ", (ir->FF >> 8), ir->FF & 0xFF); - printf("%d,%d,%d, ", ir->code[0], ir->code[1], ir->code[2]); - - len = (ir->code[1] * 2) + (ir->code[2] * 2); - for (i = 0; i < len; i++) { - printf("%s%d", !i ? "" : (i&1 ? "," : ", "), ir->code[i+3]); - } - - printf("};\n"); - -} - -//+============================================================================= -// -int main ( ) -{ - pronto_t pCode; - irCode_t irCode; - - decode(prontoTest, &pCode, &irCode); - - irDump(&irCode); - - return 0; -} - -#endif //0 diff --git a/lib/Arduino-IRremote/irRecv.cpp b/lib/Arduino-IRremote/irRecv.cpp deleted file mode 100644 index de3d3b1b..00000000 --- a/lib/Arduino-IRremote/irRecv.cpp +++ /dev/null @@ -1,235 +0,0 @@ -#include "IRremote.h" -#include "IRremoteInt.h" - -#ifdef IR_TIMER_USE_ESP32 -hw_timer_t *timer; -void IRTimer(); // defined in IRremote.cpp -#endif - -//+============================================================================= -// Decodes the received IR message -// Returns 0 if no data ready, 1 if data ready. -// Results of decoding are stored in results -// -int IRrecv::decode (decode_results *results) -{ - results->rawbuf = irparams.rawbuf; - results->rawlen = irparams.rawlen; - - results->overflow = irparams.overflow; - - if (irparams.rcvstate != STATE_STOP) return false ; - -#if DECODE_NEC - DBG_PRINTLN("Attempting NEC decode"); - if (decodeNEC(results)) return true ; -#endif - -#if DECODE_SONY - DBG_PRINTLN("Attempting Sony decode"); - if (decodeSony(results)) return true ; -#endif - -#if DECODE_SANYO - DBG_PRINTLN("Attempting Sanyo decode"); - if (decodeSanyo(results)) return true ; -#endif - -#if DECODE_MITSUBISHI - DBG_PRINTLN("Attempting Mitsubishi decode"); - if (decodeMitsubishi(results)) return true ; -#endif - -#if DECODE_RC5 - DBG_PRINTLN("Attempting RC5 decode"); - if (decodeRC5(results)) return true ; -#endif - -#if DECODE_RC6 - DBG_PRINTLN("Attempting RC6 decode"); - if (decodeRC6(results)) return true ; -#endif - -#if DECODE_PANASONIC - DBG_PRINTLN("Attempting Panasonic decode"); - if (decodePanasonic(results)) return true ; -#endif - -#if DECODE_LG - DBG_PRINTLN("Attempting LG decode"); - if (decodeLG(results)) return true ; -#endif - -#if DECODE_JVC - DBG_PRINTLN("Attempting JVC decode"); - if (decodeJVC(results)) return true ; -#endif - -#if DECODE_SAMSUNG - DBG_PRINTLN("Attempting SAMSUNG decode"); - if (decodeSAMSUNG(results)) return true ; -#endif - -#if DECODE_WHYNTER - DBG_PRINTLN("Attempting Whynter decode"); - if (decodeWhynter(results)) return true ; -#endif - -#if DECODE_AIWA_RC_T501 - DBG_PRINTLN("Attempting Aiwa RC-T501 decode"); - if (decodeAiwaRCT501(results)) return true ; -#endif - -#if DECODE_DENON - DBG_PRINTLN("Attempting Denon decode"); - if (decodeDenon(results)) return true ; -#endif - -#if DECODE_LEGO_PF - DBG_PRINTLN("Attempting Lego Power Functions"); - if (decodeLegoPowerFunctions(results)) return true ; -#endif - - // decodeHash returns a hash on any input. - // Thus, it needs to be last in the list. - // If you add any decodes, add them before this. - if (decodeHash(results)) return true ; - - // Throw away and start over - resume(); - return false; -} - -//+============================================================================= -IRrecv::IRrecv (int recvpin) -{ - irparams.recvpin = recvpin; - irparams.blinkflag = 0; -} - -IRrecv::IRrecv (int recvpin, int blinkpin) -{ - irparams.recvpin = recvpin; - irparams.blinkpin = blinkpin; - pinMode(blinkpin, OUTPUT); - irparams.blinkflag = 0; -} - - - -//+============================================================================= -// initialization -// -void IRrecv::enableIRIn ( ) -{ -// Interrupt Service Routine - Fires every 50uS -#ifdef ESP32 - // ESP32 has a proper API to setup timers, no weird chip macros needed - // simply call the readable API versions :) - // 3 timers, choose #1, 80 divider nanosecond precision, 1 to count up - timer = timerBegin(1, 80, 1); - timerAttachInterrupt(timer, &IRTimer, 1); - // every 50ns, autoreload = true - timerAlarmWrite(timer, 50, true); - timerAlarmEnable(timer); -#else - cli(); - // Setup pulse clock timer interrupt - // Prescale /8 (16M/8 = 0.5 microseconds per tick) - // Therefore, the timer interval can range from 0.5 to 128 microseconds - // Depending on the reset value (255 to 0) - TIMER_CONFIG_NORMAL(); - - // Timer2 Overflow Interrupt Enable - TIMER_ENABLE_INTR; - - TIMER_RESET; - - sei(); // enable interrupts -#endif - - // Initialize state machine variables - irparams.rcvstate = STATE_IDLE; - irparams.rawlen = 0; - - // Set pin modes - pinMode(irparams.recvpin, INPUT); -} - -//+============================================================================= -// Enable/disable blinking of pin 13 on IR processing -// -void IRrecv::blink13 (int blinkflag) -{ - irparams.blinkflag = blinkflag; - if (blinkflag) pinMode(BLINKLED, OUTPUT) ; -} - -//+============================================================================= -// Return if receiving new IR signals -// -bool IRrecv::isIdle ( ) -{ - return (irparams.rcvstate == STATE_IDLE || irparams.rcvstate == STATE_STOP) ? true : false; -} -//+============================================================================= -// Restart the ISR state machine -// -void IRrecv::resume ( ) -{ - irparams.rcvstate = STATE_IDLE; - irparams.rawlen = 0; -} - -//+============================================================================= -// hashdecode - decode an arbitrary IR code. -// Instead of decoding using a standard encoding scheme -// (e.g. Sony, NEC, RC5), the code is hashed to a 32-bit value. -// -// The algorithm: look at the sequence of MARK signals, and see if each one -// is shorter (0), the same length (1), or longer (2) than the previous. -// Do the same with the SPACE signals. Hash the resulting sequence of 0's, -// 1's, and 2's to a 32-bit value. This will give a unique value for each -// different code (probably), for most code systems. -// -// http://arcfn.com/2010/01/using-arbitrary-remotes-with-arduino.html -// -// Compare two tick values, returning 0 if newval is shorter, -// 1 if newval is equal, and 2 if newval is longer -// Use a tolerance of 20% -// -int IRrecv::compare (unsigned int oldval, unsigned int newval) -{ - if (newval < oldval * .8) return 0 ; - else if (oldval < newval * .8) return 2 ; - else return 1 ; -} - -//+============================================================================= -// Use FNV hash algorithm: http://isthe.com/chongo/tech/comp/fnv/#FNV-param -// Converts the raw code values into a 32-bit hash code. -// Hopefully this code is unique for each button. -// This isn't a "real" decoding, just an arbitrary value. -// -#define FNV_PRIME_32 16777619 -#define FNV_BASIS_32 2166136261 - -long IRrecv::decodeHash (decode_results *results) -{ - long hash = FNV_BASIS_32; - - // Require at least 6 samples to prevent triggering on noise - if (results->rawlen < 6) return false ; - - for (int i = 1; (i + 2) < results->rawlen; i++) { - int value = compare(results->rawbuf[i], results->rawbuf[i+2]); - // Add value into the hash - hash = (hash * FNV_PRIME_32) ^ value; - } - - results->value = hash; - results->bits = 32; - results->decode_type = UNKNOWN; - - return true; -} diff --git a/lib/Arduino-IRremote/irSend.cpp b/lib/Arduino-IRremote/irSend.cpp deleted file mode 100644 index c3ef3ffa..00000000 --- a/lib/Arduino-IRremote/irSend.cpp +++ /dev/null @@ -1,90 +0,0 @@ -#include "IRremote.h" -#include "IRremoteInt.h" - -//+============================================================================= -void IRsend::sendRaw (const unsigned int buf[], unsigned int len, unsigned int hz) -{ - // Set IR carrier frequency - enableIROut(hz); - - for (unsigned int i = 0; i < len; i++) { - if (i & 1) space(buf[i]) ; - else mark (buf[i]) ; - } - - space(0); // Always end with the LED off -} - -//+============================================================================= -// Sends an IR mark for the specified number of microseconds. -// The mark output is modulated at the PWM frequency. -// -void IRsend::mark (unsigned int time) -{ - TIMER_ENABLE_PWM; // Enable pin 3 PWM output - if (time > 0) custom_delay_usec(time); -} - -//+============================================================================= -// Leave pin off for time (given in microseconds) -// Sends an IR space for the specified number of microseconds. -// A space is no output, so the PWM output is disabled. -// -void IRsend::space (unsigned int time) -{ - TIMER_DISABLE_PWM; // Disable pin 3 PWM output - if (time > 0) IRsend::custom_delay_usec(time); -} - - - - - -//+============================================================================= -// Enables IR output. The khz value controls the modulation frequency in kilohertz. -// The IR output will be on pin 3 (OC2B). -// This routine is designed for 36-40KHz; if you use it for other values, it's up to you -// to make sure it gives reasonable results. (Watch out for overflow / underflow / rounding.) -// TIMER2 is used in phase-correct PWM mode, with OCR2A controlling the frequency and OCR2B -// controlling the duty cycle. -// There is no prescaling, so the output frequency is 16MHz / (2 * OCR2A) -// To turn the output on and off, we leave the PWM running, but connect and disconnect the output pin. -// A few hours staring at the ATmega documentation and this will all make sense. -// See my Secrets of Arduino PWM at http://arcfn.com/2009/07/secrets-of-arduino-pwm.html for details. -// -void IRsend::enableIROut (int khz) -{ -// FIXME: implement ESP32 support, see IR_TIMER_USE_ESP32 in boarddefs.h -#ifndef ESP32 - // Disable the Timer2 Interrupt (which is used for receiving IR) - TIMER_DISABLE_INTR; //Timer2 Overflow Interrupt - - pinMode(TIMER_PWM_PIN, OUTPUT); - digitalWrite(TIMER_PWM_PIN, LOW); // When not sending PWM, we want it low - - // COM2A = 00: disconnect OC2A - // COM2B = 00: disconnect OC2B; to send signal set to 10: OC2B non-inverted - // WGM2 = 101: phase-correct PWM with OCRA as top - // CS2 = 000: no prescaling - // The top value for the timer. The modulation frequency will be SYSCLOCK / 2 / OCR2A. - TIMER_CONFIG_KHZ(khz); -#endif -} - -//+============================================================================= -// Custom delay function that circumvents Arduino's delayMicroseconds limit - -void IRsend::custom_delay_usec(unsigned long uSecs) { - if (uSecs > 4) { - unsigned long start = micros(); - unsigned long endMicros = start + uSecs - 4; - if (endMicros < start) { // Check if overflow - while ( micros() > start ) {} // wait until overflow - } - while ( micros() < endMicros ) {} // normal wait - } - //else { - // __asm__("nop\n\t"); // must have or compiler optimizes out - //} -} - diff --git a/lib/Arduino-IRremote/ir_Aiwa.cpp b/lib/Arduino-IRremote/ir_Aiwa.cpp deleted file mode 100644 index ee4d46e8..00000000 --- a/lib/Arduino-IRremote/ir_Aiwa.cpp +++ /dev/null @@ -1,105 +0,0 @@ -#include "IRremote.h" -#include "IRremoteInt.h" - -//============================================================================== -// AAA IIIII W W AAA -// A A I W W A A -// AAAAA I W W W AAAAA -// A A I W W W A A -// A A IIIII WWW A A -//============================================================================== - -// Based off the RC-T501 RCU -// Lirc file http://lirc.sourceforge.net/remotes/aiwa/RC-T501 - -#define AIWA_RC_T501_HZ 38 -#define AIWA_RC_T501_BITS 15 -#define AIWA_RC_T501_PRE_BITS 26 -#define AIWA_RC_T501_POST_BITS 1 -#define AIWA_RC_T501_SUM_BITS (AIWA_RC_T501_PRE_BITS + AIWA_RC_T501_BITS + AIWA_RC_T501_POST_BITS) -#define AIWA_RC_T501_HDR_MARK 8800 -#define AIWA_RC_T501_HDR_SPACE 4500 -#define AIWA_RC_T501_BIT_MARK 500 -#define AIWA_RC_T501_ONE_SPACE 600 -#define AIWA_RC_T501_ZERO_SPACE 1700 - -//+============================================================================= -#if SEND_AIWA_RC_T501 -void IRsend::sendAiwaRCT501 (int code) -{ - unsigned long pre = 0x0227EEC0; // 26-bits - - // Set IR carrier frequency - enableIROut(AIWA_RC_T501_HZ); - - // Header - mark(AIWA_RC_T501_HDR_MARK); - space(AIWA_RC_T501_HDR_SPACE); - - // Send "pre" data - for (unsigned long mask = 1UL << (26 - 1); mask; mask >>= 1) { - mark(AIWA_RC_T501_BIT_MARK); - if (pre & mask) space(AIWA_RC_T501_ONE_SPACE) ; - else space(AIWA_RC_T501_ZERO_SPACE) ; - } - -//-v- THIS CODE LOOKS LIKE IT MIGHT BE WRONG - CHECK! -// it only send 15bits and ignores the top bit -// then uses TOPBIT which is 0x80000000 to check the bit code -// I suspect TOPBIT should be changed to 0x00008000 - - // Skip first code bit - code <<= 1; - // Send code - for (int i = 0; i < 15; i++) { - mark(AIWA_RC_T501_BIT_MARK); - if (code & 0x80000000) space(AIWA_RC_T501_ONE_SPACE) ; - else space(AIWA_RC_T501_ZERO_SPACE) ; - code <<= 1; - } - -//-^- THIS CODE LOOKS LIKE IT MIGHT BE WRONG - CHECK! - - // POST-DATA, 1 bit, 0x0 - mark(AIWA_RC_T501_BIT_MARK); - space(AIWA_RC_T501_ZERO_SPACE); - - mark(AIWA_RC_T501_BIT_MARK); - space(0); -} -#endif - -//+============================================================================= -#if DECODE_AIWA_RC_T501 -bool IRrecv::decodeAiwaRCT501 (decode_results *results) -{ - int data = 0; - int offset = 1; - - // Check SIZE - if (irparams.rawlen < 2 * (AIWA_RC_T501_SUM_BITS) + 4) return false ; - - // Check HDR Mark/Space - if (!MATCH_MARK (results->rawbuf[offset++], AIWA_RC_T501_HDR_MARK )) return false ; - if (!MATCH_SPACE(results->rawbuf[offset++], AIWA_RC_T501_HDR_SPACE)) return false ; - - offset += 26; // skip pre-data - optional - while(offset < irparams.rawlen - 4) { - if (MATCH_MARK(results->rawbuf[offset], AIWA_RC_T501_BIT_MARK)) offset++ ; - else return false ; - - // ONE & ZERO - if (MATCH_SPACE(results->rawbuf[offset], AIWA_RC_T501_ONE_SPACE)) data = (data << 1) | 1 ; - else if (MATCH_SPACE(results->rawbuf[offset], AIWA_RC_T501_ZERO_SPACE)) data = (data << 1) | 0 ; - else break ; // End of one & zero detected - offset++; - } - - results->bits = (offset - 1) / 2; - if (results->bits < 42) return false ; - - results->value = data; - results->decode_type = AIWA_RC_T501; - return true; -} -#endif diff --git a/lib/Arduino-IRremote/ir_Denon.cpp b/lib/Arduino-IRremote/ir_Denon.cpp deleted file mode 100644 index 4c9a502a..00000000 --- a/lib/Arduino-IRremote/ir_Denon.cpp +++ /dev/null @@ -1,94 +0,0 @@ -#include "IRremote.h" -#include "IRremoteInt.h" - -// Reverse Engineered by looking at RAW dumps generated by IRremote - -// I have since discovered that Denon publish all their IR codes: -// https://www.google.co.uk/search?q=DENON+MASTER+IR+Hex+Command+Sheet -// -> http://assets.denon.com/documentmaster/us/denon%20master%20ir%20hex.xls - -// Having looked at the official Denon Pronto sheet and reverse engineered -// the timing values from it, it is obvious that Denon have a range of -// different timings and protocols ...the values here work for my AVR-3801 Amp! - -//============================================================================== -// DDDD EEEEE N N OOO N N -// D D E NN N O O NN N -// D D EEE N N N O O N N N -// D D E N NN O O N NN -// DDDD EEEEE N N OOO N N -//============================================================================== - -#define BITS 14 // The number of bits in the command - -#define HDR_MARK 300 // The length of the Header:Mark -#define HDR_SPACE 750 // The lenght of the Header:Space - -#define BIT_MARK 300 // The length of a Bit:Mark -#define ONE_SPACE 1800 // The length of a Bit:Space for 1's -#define ZERO_SPACE 750 // The length of a Bit:Space for 0's - -//+============================================================================= -// -#if SEND_DENON -void IRsend::sendDenon (unsigned long data, int nbits) -{ - // Set IR carrier frequency - enableIROut(38); - - // Header - mark (HDR_MARK); - space(HDR_SPACE); - - // Data - for (unsigned long mask = 1UL << (nbits - 1); mask; mask >>= 1) { - if (data & mask) { - mark (BIT_MARK); - space(ONE_SPACE); - } else { - mark (BIT_MARK); - space(ZERO_SPACE); - } - } - - // Footer - mark(BIT_MARK); - space(0); // Always end with the LED off -} -#endif - -//+============================================================================= -// -#if DECODE_DENON -bool IRrecv::decodeDenon (decode_results *results) -{ - unsigned long data = 0; // Somewhere to build our code - int offset = 1; // Skip the Gap reading - - // Check we have the right amount of data - if (irparams.rawlen != 1 + 2 + (2 * BITS) + 1) return false ; - - // Check initial Mark+Space match - if (!MATCH_MARK (results->rawbuf[offset++], HDR_MARK )) return false ; - if (!MATCH_SPACE(results->rawbuf[offset++], HDR_SPACE)) return false ; - - // Read the bits in - for (int i = 0; i < BITS; i++) { - // Each bit looks like: MARK + SPACE_1 -> 1 - // or : MARK + SPACE_0 -> 0 - if (!MATCH_MARK(results->rawbuf[offset++], BIT_MARK)) return false ; - - // IR data is big-endian, so we shuffle it in from the right: - if (MATCH_SPACE(results->rawbuf[offset], ONE_SPACE)) data = (data << 1) | 1 ; - else if (MATCH_SPACE(results->rawbuf[offset], ZERO_SPACE)) data = (data << 1) | 0 ; - else return false ; - offset++; - } - - // Success - results->bits = BITS; - results->value = data; - results->decode_type = DENON; - return true; -} -#endif diff --git a/lib/Arduino-IRremote/ir_Dish.cpp b/lib/Arduino-IRremote/ir_Dish.cpp deleted file mode 100644 index 0a17a603..00000000 --- a/lib/Arduino-IRremote/ir_Dish.cpp +++ /dev/null @@ -1,54 +0,0 @@ -#include "IRremote.h" -#include "IRremoteInt.h" - -//============================================================================== -// DDDD IIIII SSSS H H -// D D I S H H -// D D I SSS HHHHH -// D D I S H H -// DDDD IIIII SSSS H H -//============================================================================== - -// Sharp and DISH support by Todd Treece ( http://unionbridge.org/design/ircommand ) -// -// The sned function needs to be repeated 4 times -// -// Only send the last for characters of the hex. -// I.E. Use 0x1C10 instead of 0x0000000000001C10 as listed in the LIRC file. -// -// Here is the LIRC file I found that seems to match the remote codes from the -// oscilloscope: -// DISH NETWORK (echostar 301): -// http://lirc.sourceforge.net/remotes/echostar/301_501_3100_5100_58xx_59xx - -#define DISH_BITS 16 -#define DISH_HDR_MARK 400 -#define DISH_HDR_SPACE 6100 -#define DISH_BIT_MARK 400 -#define DISH_ONE_SPACE 1700 -#define DISH_ZERO_SPACE 2800 -#define DISH_RPT_SPACE 6200 - -//+============================================================================= -#if SEND_DISH -void IRsend::sendDISH (unsigned long data, int nbits) -{ - // Set IR carrier frequency - enableIROut(56); - - mark(DISH_HDR_MARK); - space(DISH_HDR_SPACE); - - for (unsigned long mask = 1UL << (nbits - 1); mask; mask >>= 1) { - if (data & mask) { - mark(DISH_BIT_MARK); - space(DISH_ONE_SPACE); - } else { - mark(DISH_BIT_MARK); - space(DISH_ZERO_SPACE); - } - } - mark(DISH_HDR_MARK); //added 26th March 2016, by AnalysIR ( https://www.AnalysIR.com ) -} -#endif - diff --git a/lib/Arduino-IRremote/ir_JVC.cpp b/lib/Arduino-IRremote/ir_JVC.cpp deleted file mode 100644 index 03d5e7c0..00000000 --- a/lib/Arduino-IRremote/ir_JVC.cpp +++ /dev/null @@ -1,101 +0,0 @@ -#include "IRremote.h" -#include "IRremoteInt.h" - -//============================================================================== -// JJJJJ V V CCCC -// J V V C -// J V V C -// J J V V C -// J V CCCC -//============================================================================== - -#define JVC_BITS 16 -#define JVC_HDR_MARK 8000 -#define JVC_HDR_SPACE 4000 -#define JVC_BIT_MARK 600 -#define JVC_ONE_SPACE 1600 -#define JVC_ZERO_SPACE 550 -#define JVC_RPT_LENGTH 60000 - -//+============================================================================= -// JVC does NOT repeat by sending a separate code (like NEC does). -// The JVC protocol repeats by skipping the header. -// To send a JVC repeat signal, send the original code value -// and set 'repeat' to true -// -#if SEND_JVC -void IRsend::sendJVC (unsigned long data, int nbits, bool repeat) -{ - // Set IR carrier frequency - enableIROut(38); - - // Only send the Header if this is NOT a repeat command - if (!repeat){ - mark(JVC_HDR_MARK); - space(JVC_HDR_SPACE); - } - - // Data - for (unsigned long mask = 1UL << (nbits - 1); mask; mask >>= 1) { - if (data & mask) { - mark(JVC_BIT_MARK); - space(JVC_ONE_SPACE); - } else { - mark(JVC_BIT_MARK); - space(JVC_ZERO_SPACE); - } - } - - // Footer - mark(JVC_BIT_MARK); - space(0); // Always end with the LED off -} -#endif - -//+============================================================================= -#if DECODE_JVC -bool IRrecv::decodeJVC (decode_results *results) -{ - long data = 0; - int offset = 1; // Skip first space - - // Check for repeat - if ( (irparams.rawlen - 1 == 33) - && MATCH_MARK(results->rawbuf[offset], JVC_BIT_MARK) - && MATCH_MARK(results->rawbuf[irparams.rawlen-1], JVC_BIT_MARK) - ) { - results->bits = 0; - results->value = REPEAT; - results->decode_type = JVC; - return true; - } - - // Initial mark - if (!MATCH_MARK(results->rawbuf[offset++], JVC_HDR_MARK)) return false ; - - if (irparams.rawlen < (2 * JVC_BITS) + 1 ) return false ; - - // Initial space - if (!MATCH_SPACE(results->rawbuf[offset++], JVC_HDR_SPACE)) return false ; - - for (int i = 0; i < JVC_BITS; i++) { - if (!MATCH_MARK(results->rawbuf[offset++], JVC_BIT_MARK)) return false ; - - if (MATCH_SPACE(results->rawbuf[offset], JVC_ONE_SPACE)) data = (data << 1) | 1 ; - else if (MATCH_SPACE(results->rawbuf[offset], JVC_ZERO_SPACE)) data = (data << 1) | 0 ; - else return false ; - offset++; - } - - // Stop bit - if (!MATCH_MARK(results->rawbuf[offset], JVC_BIT_MARK)) return false ; - - // Success - results->bits = JVC_BITS; - results->value = data; - results->decode_type = JVC; - - return true; -} -#endif - diff --git a/lib/Arduino-IRremote/ir_LG.cpp b/lib/Arduino-IRremote/ir_LG.cpp deleted file mode 100644 index 27bea287..00000000 --- a/lib/Arduino-IRremote/ir_LG.cpp +++ /dev/null @@ -1,80 +0,0 @@ -#include "IRremote.h" -#include "IRremoteInt.h" - -//============================================================================== -// L GGGG -// L G -// L G GG -// L G G -// LLLLL GGG -//============================================================================== - -#define LG_BITS 28 - -#define LG_HDR_MARK 8000 -#define LG_HDR_SPACE 4000 -#define LG_BIT_MARK 600 -#define LG_ONE_SPACE 1600 -#define LG_ZERO_SPACE 550 -#define LG_RPT_LENGTH 60000 - -//+============================================================================= -#if DECODE_LG -bool IRrecv::decodeLG (decode_results *results) -{ - long data = 0; - int offset = 1; // Skip first space - - // Check we have the right amount of data - if (irparams.rawlen < (2 * LG_BITS) + 1 ) return false ; - - // Initial mark/space - if (!MATCH_MARK(results->rawbuf[offset++], LG_HDR_MARK)) return false ; - if (!MATCH_SPACE(results->rawbuf[offset++], LG_HDR_SPACE)) return false ; - - for (int i = 0; i < LG_BITS; i++) { - if (!MATCH_MARK(results->rawbuf[offset++], LG_BIT_MARK)) return false ; - - if (MATCH_SPACE(results->rawbuf[offset], LG_ONE_SPACE)) data = (data << 1) | 1 ; - else if (MATCH_SPACE(results->rawbuf[offset], LG_ZERO_SPACE)) data = (data << 1) | 0 ; - else return false ; - offset++; - } - - // Stop bit - if (!MATCH_MARK(results->rawbuf[offset], LG_BIT_MARK)) return false ; - - // Success - results->bits = LG_BITS; - results->value = data; - results->decode_type = LG; - return true; -} -#endif - -//+============================================================================= -#if SEND_LG -void IRsend::sendLG (unsigned long data, int nbits) -{ - // Set IR carrier frequency - enableIROut(38); - - // Header - mark(LG_HDR_MARK); - space(LG_HDR_SPACE); - mark(LG_BIT_MARK); - - // Data - for (unsigned long mask = 1UL << (nbits - 1); mask; mask >>= 1) { - if (data & mask) { - space(LG_ONE_SPACE); - mark(LG_BIT_MARK); - } else { - space(LG_ZERO_SPACE); - mark(LG_BIT_MARK); - } - } - space(0); // Always end with the LED off -} -#endif - diff --git a/lib/Arduino-IRremote/ir_Lego_PF.cpp b/lib/Arduino-IRremote/ir_Lego_PF.cpp deleted file mode 100644 index 91902c50..00000000 --- a/lib/Arduino-IRremote/ir_Lego_PF.cpp +++ /dev/null @@ -1,46 +0,0 @@ -#include "IRremote.h" -#include "IRremoteInt.h" -#include "ir_Lego_PF_BitStreamEncoder.h" - -//============================================================================== -// L EEEEEE EEEE OOOO -// L E E O O -// L EEEE E EEE O O -// L E E E O O LEGO Power Functions -// LLLLLL EEEEEE EEEE OOOO Copyright (c) 2016 Philipp Henkel -//============================================================================== - -// Supported Devices -// LEGO® Power Functions IR Receiver 8884 - -//+============================================================================= -// -#if SEND_LEGO_PF - -#if DEBUG -namespace { -void logFunctionParameters(uint16_t data, bool repeat) { - DBG_PRINT("sendLegoPowerFunctions(data="); - DBG_PRINT(data); - DBG_PRINT(", repeat="); - DBG_PRINTLN(repeat?"true)" : "false)"); -} -} // anonymous namespace -#endif // DEBUG - -void IRsend::sendLegoPowerFunctions(uint16_t data, bool repeat) -{ -#if DEBUG - ::logFunctionParameters(data, repeat); -#endif // DEBUG - - enableIROut(38); - static LegoPfBitStreamEncoder bitStreamEncoder; - bitStreamEncoder.reset(data, repeat); - do { - mark(bitStreamEncoder.getMarkDuration()); - space(bitStreamEncoder.getPauseDuration()); - } while (bitStreamEncoder.next()); -} - -#endif // SEND_LEGO_PF diff --git a/lib/Arduino-IRremote/ir_Lego_PF_BitStreamEncoder.h b/lib/Arduino-IRremote/ir_Lego_PF_BitStreamEncoder.h deleted file mode 100644 index 3cd6fb5e..00000000 --- a/lib/Arduino-IRremote/ir_Lego_PF_BitStreamEncoder.h +++ /dev/null @@ -1,115 +0,0 @@ - -//============================================================================== -// L EEEEEE EEEE OOOO -// L E E O O -// L EEEE E EEE O O -// L E E E O O LEGO Power Functions -// LLLLLL EEEEEE EEEE OOOO Copyright (c) 2016, 2017 Philipp Henkel -//============================================================================== - -//+============================================================================= -// - -class LegoPfBitStreamEncoder { - private: - uint16_t data; - bool repeatMessage; - uint8_t messageBitIdx; - uint8_t repeatCount; - uint16_t messageLength; - - public: - // HIGH data bit = IR mark + high pause - // LOW data bit = IR mark + low pause - static const uint16_t LOW_BIT_DURATION = 421; - static const uint16_t HIGH_BIT_DURATION = 711; - static const uint16_t START_BIT_DURATION = 1184; - static const uint16_t STOP_BIT_DURATION = 1184; - static const uint8_t IR_MARK_DURATION = 158; - static const uint16_t HIGH_PAUSE_DURATION = HIGH_BIT_DURATION - IR_MARK_DURATION; - static const uint16_t LOW_PAUSE_DURATION = LOW_BIT_DURATION - IR_MARK_DURATION; - static const uint16_t START_PAUSE_DURATION = START_BIT_DURATION - IR_MARK_DURATION; - static const uint16_t STOP_PAUSE_DURATION = STOP_BIT_DURATION - IR_MARK_DURATION; - static const uint8_t MESSAGE_BITS = 18; - static const uint16_t MAX_MESSAGE_LENGTH = 16000; - - void reset(uint16_t data, bool repeatMessage) { - this->data = data; - this->repeatMessage = repeatMessage; - messageBitIdx = 0; - repeatCount = 0; - messageLength = getMessageLength(); - } - - int getChannelId() const { return 1 + ((data >> 12) & 0x3); } - - uint16_t getMessageLength() const { - // Sum up all marks - uint16_t length = MESSAGE_BITS * IR_MARK_DURATION; - - // Sum up all pauses - length += START_PAUSE_DURATION; - for (unsigned long mask = 1UL << 15; mask; mask >>= 1) { - if (data & mask) { - length += HIGH_PAUSE_DURATION; - } else { - length += LOW_PAUSE_DURATION; - } - } - length += STOP_PAUSE_DURATION; - return length; - } - - boolean next() { - messageBitIdx++; - if (messageBitIdx >= MESSAGE_BITS) { - repeatCount++; - messageBitIdx = 0; - } - if (repeatCount >= 1 && !repeatMessage) { - return false; - } else if (repeatCount >= 5) { - return false; - } else { - return true; - } - } - - uint8_t getMarkDuration() const { return IR_MARK_DURATION; } - - uint32_t getPauseDuration() const { - if (messageBitIdx == 0) - return START_PAUSE_DURATION; - else if (messageBitIdx < MESSAGE_BITS - 1) { - return getDataBitPause(); - } else { - return getStopPause(); - } - } - - private: - uint16_t getDataBitPause() const { - const int pos = MESSAGE_BITS - 2 - messageBitIdx; - const bool isHigh = data & (1 << pos); - return isHigh ? HIGH_PAUSE_DURATION : LOW_PAUSE_DURATION; - } - - uint32_t getStopPause() const { - if (repeatMessage) { - return getRepeatStopPause(); - } else { - return STOP_PAUSE_DURATION; - } - } - - uint32_t getRepeatStopPause() const { - if (repeatCount == 0 || repeatCount == 1) { - return STOP_PAUSE_DURATION + (uint32_t)5 * MAX_MESSAGE_LENGTH - messageLength; - } else if (repeatCount == 2 || repeatCount == 3) { - return STOP_PAUSE_DURATION - + (uint32_t)(6 + 2 * getChannelId()) * MAX_MESSAGE_LENGTH - messageLength; - } else { - return STOP_PAUSE_DURATION; - } - } -}; diff --git a/lib/Arduino-IRremote/ir_Mitsubishi.cpp b/lib/Arduino-IRremote/ir_Mitsubishi.cpp deleted file mode 100644 index 5068a262..00000000 --- a/lib/Arduino-IRremote/ir_Mitsubishi.cpp +++ /dev/null @@ -1,85 +0,0 @@ -#include "IRremote.h" -#include "IRremoteInt.h" - -//============================================================================== -// MMMMM IIIII TTTTT SSSS U U BBBB IIIII SSSS H H IIIII -// M M M I T S U U B B I S H H I -// M M M I T SSS U U BBBB I SSS HHHHH I -// M M I T S U U B B I S H H I -// M M IIIII T SSSS UUU BBBBB IIIII SSSS H H IIIII -//============================================================================== - -// Looks like Sony except for timings, 48 chars of data and time/space different - -#define MITSUBISHI_BITS 16 - -// Mitsubishi RM 75501 -// 14200 7 41 7 42 7 42 7 17 7 17 7 18 7 41 7 18 7 17 7 17 7 18 7 41 8 17 7 17 7 18 7 17 7 -// #define MITSUBISHI_HDR_MARK 250 // seen range 3500 -#define MITSUBISHI_HDR_SPACE 350 // 7*50+100 -#define MITSUBISHI_ONE_MARK 1950 // 41*50-100 -#define MITSUBISHI_ZERO_MARK 750 // 17*50-100 -// #define MITSUBISHI_DOUBLE_SPACE_USECS 800 // usually ssee 713 - not using ticks as get number wrapround -// #define MITSUBISHI_RPT_LENGTH 45000 - -//+============================================================================= -#if DECODE_MITSUBISHI -bool IRrecv::decodeMitsubishi (decode_results *results) -{ - // Serial.print("?!? decoding Mitsubishi:");Serial.print(irparams.rawlen); Serial.print(" want "); Serial.println( 2 * MITSUBISHI_BITS + 2); - long data = 0; - if (irparams.rawlen < 2 * MITSUBISHI_BITS + 2) return false ; - int offset = 0; // Skip first space - // Initial space - -#if 0 - // Put this back in for debugging - note can't use #DEBUG as if Debug on we don't see the repeat cos of the delay - Serial.print("IR Gap: "); - Serial.println( results->rawbuf[offset]); - Serial.println( "test against:"); - Serial.println(results->rawbuf[offset]); -#endif - -#if 0 - // Not seeing double keys from Mitsubishi - if (results->rawbuf[offset] < MITSUBISHI_DOUBLE_SPACE_USECS) { - // Serial.print("IR Gap found: "); - results->bits = 0; - results->value = REPEAT; - results->decode_type = MITSUBISHI; - return true; - } -#endif - - offset++; - - // Typical - // 14200 7 41 7 42 7 42 7 17 7 17 7 18 7 41 7 18 7 17 7 17 7 18 7 41 8 17 7 17 7 18 7 17 7 - - // Initial Space - if (!MATCH_MARK(results->rawbuf[offset], MITSUBISHI_HDR_SPACE)) return false ; - offset++; - - while (offset + 1 < irparams.rawlen) { - if (MATCH_MARK(results->rawbuf[offset], MITSUBISHI_ONE_MARK)) data = (data << 1) | 1 ; - else if (MATCH_MARK(results->rawbuf[offset], MITSUBISHI_ZERO_MARK)) data <<= 1 ; - else return false ; - offset++; - - if (!MATCH_SPACE(results->rawbuf[offset], MITSUBISHI_HDR_SPACE)) break ; - offset++; - } - - // Success - results->bits = (offset - 1) / 2; - if (results->bits < MITSUBISHI_BITS) { - results->bits = 0; - return false; - } - - results->value = data; - results->decode_type = MITSUBISHI; - return true; -} -#endif - diff --git a/lib/Arduino-IRremote/ir_NEC.cpp b/lib/Arduino-IRremote/ir_NEC.cpp deleted file mode 100644 index 4443a4de..00000000 --- a/lib/Arduino-IRremote/ir_NEC.cpp +++ /dev/null @@ -1,98 +0,0 @@ -#include "IRremote.h" -#include "IRremoteInt.h" - -//============================================================================== -// N N EEEEE CCCC -// NN N E C -// N N N EEE C -// N NN E C -// N N EEEEE CCCC -//============================================================================== - -#define NEC_BITS 32 -#define NEC_HDR_MARK 9000 -#define NEC_HDR_SPACE 4500 -#define NEC_BIT_MARK 560 -#define NEC_ONE_SPACE 1690 -#define NEC_ZERO_SPACE 560 -#define NEC_RPT_SPACE 2250 - -//+============================================================================= -#if SEND_NEC -void IRsend::sendNEC (unsigned long data, int nbits) -{ - // Set IR carrier frequency - enableIROut(38); - - // Header - mark(NEC_HDR_MARK); - space(NEC_HDR_SPACE); - - // Data - for (unsigned long mask = 1UL << (nbits - 1); mask; mask >>= 1) { - if (data & mask) { - mark(NEC_BIT_MARK); - space(NEC_ONE_SPACE); - } else { - mark(NEC_BIT_MARK); - space(NEC_ZERO_SPACE); - } - } - - // Footer - mark(NEC_BIT_MARK); - space(0); // Always end with the LED off -} -#endif - -//+============================================================================= -// NECs have a repeat only 4 items long -// -#if DECODE_NEC -bool IRrecv::decodeNEC (decode_results *results) -{ - long data = 0; // We decode in to here; Start with nothing - int offset = 1; // Index in to results; Skip first entry!? - - // Check header "mark" - if (!MATCH_MARK(results->rawbuf[offset], NEC_HDR_MARK)) return false ; - offset++; - - // Check for repeat - if ( (irparams.rawlen == 4) - && MATCH_SPACE(results->rawbuf[offset ], NEC_RPT_SPACE) - && MATCH_MARK (results->rawbuf[offset+1], NEC_BIT_MARK ) - ) { - results->bits = 0; - results->value = REPEAT; - results->decode_type = NEC; - return true; - } - - // Check we have enough data - if (irparams.rawlen < (2 * NEC_BITS) + 4) return false ; - - // Check header "space" - if (!MATCH_SPACE(results->rawbuf[offset], NEC_HDR_SPACE)) return false ; - offset++; - - // Build the data - for (int i = 0; i < NEC_BITS; i++) { - // Check data "mark" - if (!MATCH_MARK(results->rawbuf[offset], NEC_BIT_MARK)) return false ; - offset++; - // Suppend this bit - if (MATCH_SPACE(results->rawbuf[offset], NEC_ONE_SPACE )) data = (data << 1) | 1 ; - else if (MATCH_SPACE(results->rawbuf[offset], NEC_ZERO_SPACE)) data = (data << 1) | 0 ; - else return false ; - offset++; - } - - // Success - results->bits = NEC_BITS; - results->value = data; - results->decode_type = NEC; - - return true; -} -#endif diff --git a/lib/Arduino-IRremote/ir_Panasonic.cpp b/lib/Arduino-IRremote/ir_Panasonic.cpp deleted file mode 100644 index bef5c5cf..00000000 --- a/lib/Arduino-IRremote/ir_Panasonic.cpp +++ /dev/null @@ -1,78 +0,0 @@ -#include "IRremote.h" -#include "IRremoteInt.h" - -//============================================================================== -// PPPP AAA N N AAA SSSS OOO N N IIIII CCCC -// P P A A NN N A A S O O NN N I C -// PPPP AAAAA N N N AAAAA SSS O O N N N I C -// P A A N NN A A S O O N NN I C -// P A A N N A A SSSS OOO N N IIIII CCCC -//============================================================================== - -#define PANASONIC_BITS 48 -#define PANASONIC_HDR_MARK 3502 -#define PANASONIC_HDR_SPACE 1750 -#define PANASONIC_BIT_MARK 502 -#define PANASONIC_ONE_SPACE 1244 -#define PANASONIC_ZERO_SPACE 400 - -//+============================================================================= -#if SEND_PANASONIC -void IRsend::sendPanasonic (unsigned int address, unsigned long data) -{ - // Set IR carrier frequency - enableIROut(35); - - // Header - mark(PANASONIC_HDR_MARK); - space(PANASONIC_HDR_SPACE); - - // Address - for (unsigned long mask = 1UL << (16 - 1); mask; mask >>= 1) { - mark(PANASONIC_BIT_MARK); - if (address & mask) space(PANASONIC_ONE_SPACE) ; - else space(PANASONIC_ZERO_SPACE) ; - } - - // Data - for (unsigned long mask = 1UL << (32 - 1); mask; mask >>= 1) { - mark(PANASONIC_BIT_MARK); - if (data & mask) space(PANASONIC_ONE_SPACE) ; - else space(PANASONIC_ZERO_SPACE) ; - } - - // Footer - mark(PANASONIC_BIT_MARK); - space(0); // Always end with the LED off -} -#endif - -//+============================================================================= -#if DECODE_PANASONIC -bool IRrecv::decodePanasonic (decode_results *results) -{ - unsigned long long data = 0; - int offset = 1; - - if (!MATCH_MARK(results->rawbuf[offset++], PANASONIC_HDR_MARK )) return false ; - if (!MATCH_MARK(results->rawbuf[offset++], PANASONIC_HDR_SPACE)) return false ; - - // decode address - for (int i = 0; i < PANASONIC_BITS; i++) { - if (!MATCH_MARK(results->rawbuf[offset++], PANASONIC_BIT_MARK)) return false ; - - if (MATCH_SPACE(results->rawbuf[offset],PANASONIC_ONE_SPACE )) data = (data << 1) | 1 ; - else if (MATCH_SPACE(results->rawbuf[offset],PANASONIC_ZERO_SPACE)) data = (data << 1) | 0 ; - else return false ; - offset++; - } - - results->value = (unsigned long)data; - results->address = (unsigned int)(data >> 32); - results->decode_type = PANASONIC; - results->bits = PANASONIC_BITS; - - return true; -} -#endif - diff --git a/lib/Arduino-IRremote/ir_RC5_RC6.cpp b/lib/Arduino-IRremote/ir_RC5_RC6.cpp deleted file mode 100644 index f7134a9f..00000000 --- a/lib/Arduino-IRremote/ir_RC5_RC6.cpp +++ /dev/null @@ -1,207 +0,0 @@ -#include "IRremote.h" -#include "IRremoteInt.h" - -//+============================================================================= -// Gets one undecoded level at a time from the raw buffer. -// The RC5/6 decoding is easier if the data is broken into time intervals. -// E.g. if the buffer has MARK for 2 time intervals and SPACE for 1, -// successive calls to getRClevel will return MARK, MARK, SPACE. -// offset and used are updated to keep track of the current position. -// t1 is the time interval for a single bit in microseconds. -// Returns -1 for error (measured time interval is not a multiple of t1). -// -#if (DECODE_RC5 || DECODE_RC6) -int IRrecv::getRClevel (decode_results *results, int *offset, int *used, int t1) -{ - int width; - int val; - int correction; - int avail; - - if (*offset >= results->rawlen) return SPACE ; // After end of recorded buffer, assume SPACE. - width = results->rawbuf[*offset]; - val = ((*offset) % 2) ? MARK : SPACE; - correction = (val == MARK) ? MARK_EXCESS : - MARK_EXCESS; - - if (MATCH(width, ( t1) + correction)) avail = 1 ; - else if (MATCH(width, (2*t1) + correction)) avail = 2 ; - else if (MATCH(width, (3*t1) + correction)) avail = 3 ; - else return -1 ; - - (*used)++; - if (*used >= avail) { - *used = 0; - (*offset)++; - } - - DBG_PRINTLN( (val == MARK) ? "MARK" : "SPACE" ); - - return val; -} -#endif - -//============================================================================== -// RRRR CCCC 55555 -// R R C 5 -// RRRR C 5555 -// R R C 5 -// R R CCCC 5555 -// -// NB: First bit must be a one (start bit) -// -#define MIN_RC5_SAMPLES 11 -#define RC5_T1 889 -#define RC5_RPT_LENGTH 46000 - -//+============================================================================= -#if SEND_RC5 -void IRsend::sendRC5 (unsigned long data, int nbits) -{ - // Set IR carrier frequency - enableIROut(36); - - // Start - mark(RC5_T1); - space(RC5_T1); - mark(RC5_T1); - - // Data - for (unsigned long mask = 1UL << (nbits - 1); mask; mask >>= 1) { - if (data & mask) { - space(RC5_T1); // 1 is space, then mark - mark(RC5_T1); - } else { - mark(RC5_T1); - space(RC5_T1); - } - } - - space(0); // Always end with the LED off -} -#endif - -//+============================================================================= -#if DECODE_RC5 -bool IRrecv::decodeRC5 (decode_results *results) -{ - int nbits; - long data = 0; - int used = 0; - int offset = 1; // Skip gap space - - if (irparams.rawlen < MIN_RC5_SAMPLES + 2) return false ; - - // Get start bits - if (getRClevel(results, &offset, &used, RC5_T1) != MARK) return false ; - if (getRClevel(results, &offset, &used, RC5_T1) != SPACE) return false ; - if (getRClevel(results, &offset, &used, RC5_T1) != MARK) return false ; - - for (nbits = 0; offset < irparams.rawlen; nbits++) { - int levelA = getRClevel(results, &offset, &used, RC5_T1); - int levelB = getRClevel(results, &offset, &used, RC5_T1); - - if ((levelA == SPACE) && (levelB == MARK )) data = (data << 1) | 1 ; - else if ((levelA == MARK ) && (levelB == SPACE)) data = (data << 1) | 0 ; - else return false ; - } - - // Success - results->bits = nbits; - results->value = data; - results->decode_type = RC5; - return true; -} -#endif - -//+============================================================================= -// RRRR CCCC 6666 -// R R C 6 -// RRRR C 6666 -// R R C 6 6 -// R R CCCC 666 -// -// NB : Caller needs to take care of flipping the toggle bit -// -#define MIN_RC6_SAMPLES 1 -#define RC6_HDR_MARK 2666 -#define RC6_HDR_SPACE 889 -#define RC6_T1 444 -#define RC6_RPT_LENGTH 46000 - -#if SEND_RC6 -void IRsend::sendRC6 (unsigned long data, int nbits) -{ - // Set IR carrier frequency - enableIROut(36); - - // Header - mark(RC6_HDR_MARK); - space(RC6_HDR_SPACE); - - // Start bit - mark(RC6_T1); - space(RC6_T1); - - // Data - for (unsigned long i = 1, mask = 1UL << (nbits - 1); mask; i++, mask >>= 1) { - // The fourth bit we send is a "double width trailer bit" - int t = (i == 4) ? (RC6_T1 * 2) : (RC6_T1) ; - if (data & mask) { - mark(t); - space(t); - } else { - space(t); - mark(t); - } - } - - space(0); // Always end with the LED off -} -#endif - -//+============================================================================= -#if DECODE_RC6 -bool IRrecv::decodeRC6 (decode_results *results) -{ - int nbits; - long data = 0; - int used = 0; - int offset = 1; // Skip first space - - if (results->rawlen < MIN_RC6_SAMPLES) return false ; - - // Initial mark - if (!MATCH_MARK(results->rawbuf[offset++], RC6_HDR_MARK)) return false ; - if (!MATCH_SPACE(results->rawbuf[offset++], RC6_HDR_SPACE)) return false ; - - // Get start bit (1) - if (getRClevel(results, &offset, &used, RC6_T1) != MARK) return false ; - if (getRClevel(results, &offset, &used, RC6_T1) != SPACE) return false ; - - for (nbits = 0; offset < results->rawlen; nbits++) { - int levelA, levelB; // Next two levels - - levelA = getRClevel(results, &offset, &used, RC6_T1); - if (nbits == 3) { - // T bit is double wide; make sure second half matches - if (levelA != getRClevel(results, &offset, &used, RC6_T1)) return false; - } - - levelB = getRClevel(results, &offset, &used, RC6_T1); - if (nbits == 3) { - // T bit is double wide; make sure second half matches - if (levelB != getRClevel(results, &offset, &used, RC6_T1)) return false; - } - - if ((levelA == MARK ) && (levelB == SPACE)) data = (data << 1) | 1 ; // inverted compared to RC5 - else if ((levelA == SPACE) && (levelB == MARK )) data = (data << 1) | 0 ; // ... - else return false ; // Error - } - - // Success - results->bits = nbits; - results->value = data; - results->decode_type = RC6; - return true; -} -#endif diff --git a/lib/Arduino-IRremote/ir_Samsung.cpp b/lib/Arduino-IRremote/ir_Samsung.cpp deleted file mode 100644 index f36185fb..00000000 --- a/lib/Arduino-IRremote/ir_Samsung.cpp +++ /dev/null @@ -1,92 +0,0 @@ -#include "IRremote.h" -#include "IRremoteInt.h" - -//============================================================================== -// SSSS AAA MMM SSSS U U N N GGGG -// S A A M M M S U U NN N G -// SSS AAAAA M M M SSS U U N N N G GG -// S A A M M S U U N NN G G -// SSSS A A M M SSSS UUU N N GGG -//============================================================================== - -#define SAMSUNG_BITS 32 -#define SAMSUNG_HDR_MARK 5000 -#define SAMSUNG_HDR_SPACE 5000 -#define SAMSUNG_BIT_MARK 560 -#define SAMSUNG_ONE_SPACE 1600 -#define SAMSUNG_ZERO_SPACE 560 -#define SAMSUNG_RPT_SPACE 2250 - -//+============================================================================= -#if SEND_SAMSUNG -void IRsend::sendSAMSUNG (unsigned long data, int nbits) -{ - // Set IR carrier frequency - enableIROut(38); - - // Header - mark(SAMSUNG_HDR_MARK); - space(SAMSUNG_HDR_SPACE); - - // Data - for (unsigned long mask = 1UL << (nbits - 1); mask; mask >>= 1) { - if (data & mask) { - mark(SAMSUNG_BIT_MARK); - space(SAMSUNG_ONE_SPACE); - } else { - mark(SAMSUNG_BIT_MARK); - space(SAMSUNG_ZERO_SPACE); - } - } - - // Footer - mark(SAMSUNG_BIT_MARK); - space(0); // Always end with the LED off -} -#endif - -//+============================================================================= -// SAMSUNGs have a repeat only 4 items long -// -#if DECODE_SAMSUNG -bool IRrecv::decodeSAMSUNG (decode_results *results) -{ - long data = 0; - int offset = 1; // Skip first space - - // Initial mark - if (!MATCH_MARK(results->rawbuf[offset], SAMSUNG_HDR_MARK)) return false ; - offset++; - - // Check for repeat - if ( (irparams.rawlen == 4) - && MATCH_SPACE(results->rawbuf[offset], SAMSUNG_RPT_SPACE) - && MATCH_MARK(results->rawbuf[offset+1], SAMSUNG_BIT_MARK) - ) { - results->bits = 0; - results->value = REPEAT; - results->decode_type = SAMSUNG; - return true; - } - if (irparams.rawlen < (2 * SAMSUNG_BITS) + 4) return false ; - - // Initial space - if (!MATCH_SPACE(results->rawbuf[offset++], SAMSUNG_HDR_SPACE)) return false ; - - for (int i = 0; i < SAMSUNG_BITS; i++) { - if (!MATCH_MARK(results->rawbuf[offset++], SAMSUNG_BIT_MARK)) return false ; - - if (MATCH_SPACE(results->rawbuf[offset], SAMSUNG_ONE_SPACE)) data = (data << 1) | 1 ; - else if (MATCH_SPACE(results->rawbuf[offset], SAMSUNG_ZERO_SPACE)) data = (data << 1) | 0 ; - else return false ; - offset++; - } - - // Success - results->bits = SAMSUNG_BITS; - results->value = data; - results->decode_type = SAMSUNG; - return true; -} -#endif - diff --git a/lib/Arduino-IRremote/ir_Sanyo.cpp b/lib/Arduino-IRremote/ir_Sanyo.cpp deleted file mode 100644 index 4a1e9fab..00000000 --- a/lib/Arduino-IRremote/ir_Sanyo.cpp +++ /dev/null @@ -1,76 +0,0 @@ -#include "IRremote.h" -#include "IRremoteInt.h" - -//============================================================================== -// SSSS AAA N N Y Y OOO -// S A A NN N Y Y O O -// SSS AAAAA N N N Y O O -// S A A N NN Y O O -// SSSS A A N N Y OOO -//============================================================================== - -// I think this is a Sanyo decoder: Serial = SA 8650B -// Looks like Sony except for timings, 48 chars of data and time/space different - -#define SANYO_BITS 12 -#define SANYO_HDR_MARK 3500 // seen range 3500 -#define SANYO_HDR_SPACE 950 // seen 950 -#define SANYO_ONE_MARK 2400 // seen 2400 -#define SANYO_ZERO_MARK 700 // seen 700 -#define SANYO_DOUBLE_SPACE_USECS 800 // usually ssee 713 - not using ticks as get number wrapround -#define SANYO_RPT_LENGTH 45000 - -//+============================================================================= -#if DECODE_SANYO -bool IRrecv::decodeSanyo (decode_results *results) -{ - long data = 0; - int offset = 0; // Skip first space <-- CHECK THIS! - - if (irparams.rawlen < (2 * SANYO_BITS) + 2) return false ; - -#if 0 - // Put this back in for debugging - note can't use #DEBUG as if Debug on we don't see the repeat cos of the delay - Serial.print("IR Gap: "); - Serial.println( results->rawbuf[offset]); - Serial.println( "test against:"); - Serial.println(results->rawbuf[offset]); -#endif - - // Initial space - if (results->rawbuf[offset] < SANYO_DOUBLE_SPACE_USECS) { - //Serial.print("IR Gap found: "); - results->bits = 0; - results->value = REPEAT; - results->decode_type = SANYO; - return true; - } - offset++; - - // Initial mark - if (!MATCH_MARK(results->rawbuf[offset++], SANYO_HDR_MARK)) return false ; - - // Skip Second Mark - if (!MATCH_MARK(results->rawbuf[offset++], SANYO_HDR_MARK)) return false ; - - while (offset + 1 < irparams.rawlen) { - if (!MATCH_SPACE(results->rawbuf[offset++], SANYO_HDR_SPACE)) break ; - - if (MATCH_MARK(results->rawbuf[offset], SANYO_ONE_MARK)) data = (data << 1) | 1 ; - else if (MATCH_MARK(results->rawbuf[offset], SANYO_ZERO_MARK)) data = (data << 1) | 0 ; - else return false ; - offset++; - } - - // Success - results->bits = (offset - 1) / 2; - if (results->bits < 12) { - results->bits = 0; - return false; - } - - results->value = data; - results->decode_type = SANYO; - return true; -} -#endif diff --git a/lib/Arduino-IRremote/ir_Sharp.cpp b/lib/Arduino-IRremote/ir_Sharp.cpp deleted file mode 100644 index f1845e03..00000000 --- a/lib/Arduino-IRremote/ir_Sharp.cpp +++ /dev/null @@ -1,71 +0,0 @@ -#include "IRremote.h" -#include "IRremoteInt.h" - -//============================================================================== -// SSSS H H AAA RRRR PPPP -// S H H A A R R P P -// SSS HHHHH AAAAA RRRR PPPP -// S H H A A R R P -// SSSS H H A A R R P -//============================================================================== - -// Sharp and DISH support by Todd Treece: http://unionbridge.org/design/ircommand -// -// The send function has the necessary repeat built in because of the need to -// invert the signal. -// -// Sharp protocol documentation: -// http://www.sbprojects.com/knowledge/ir/sharp.htm -// -// Here is the LIRC file I found that seems to match the remote codes from the -// oscilloscope: -// Sharp LCD TV: -// http://lirc.sourceforge.net/remotes/sharp/GA538WJSA - -#define SHARP_BITS 15 -#define SHARP_BIT_MARK 245 -#define SHARP_ONE_SPACE 1805 -#define SHARP_ZERO_SPACE 795 -#define SHARP_GAP 600000 -#define SHARP_RPT_SPACE 3000 - -#define SHARP_TOGGLE_MASK 0x3FF - -//+============================================================================= -#if SEND_SHARP -void IRsend::sendSharpRaw (unsigned long data, int nbits) -{ - enableIROut(38); - - // Sending codes in bursts of 3 (normal, inverted, normal) makes transmission - // much more reliable. That's the exact behaviour of CD-S6470 remote control. - for (int n = 0; n < 3; n++) { - for (unsigned long mask = 1UL << (nbits - 1); mask; mask >>= 1) { - if (data & mask) { - mark(SHARP_BIT_MARK); - space(SHARP_ONE_SPACE); - } else { - mark(SHARP_BIT_MARK); - space(SHARP_ZERO_SPACE); - } - } - - mark(SHARP_BIT_MARK); - space(SHARP_ZERO_SPACE); - delay(40); - - data = data ^ SHARP_TOGGLE_MASK; - } -} -#endif - -//+============================================================================= -// Sharp send compatible with data obtained through decodeSharp() -// ^^^^^^^^^^^^^ FUNCTION MISSING! -// -#if SEND_SHARP -void IRsend::sendSharp (unsigned int address, unsigned int command) -{ - sendSharpRaw((address << 10) | (command << 2) | 2, SHARP_BITS); -} -#endif diff --git a/lib/Arduino-IRremote/ir_Sony.cpp b/lib/Arduino-IRremote/ir_Sony.cpp deleted file mode 100644 index 95b710e4..00000000 --- a/lib/Arduino-IRremote/ir_Sony.cpp +++ /dev/null @@ -1,95 +0,0 @@ -#include "IRremote.h" -#include "IRremoteInt.h" - -//============================================================================== -// SSSS OOO N N Y Y -// S O O NN N Y Y -// SSS O O N N N Y -// S O O N NN Y -// SSSS OOO N N Y -//============================================================================== - -#define SONY_BITS 12 -#define SONY_HDR_MARK 2400 -#define SONY_HDR_SPACE 600 -#define SONY_ONE_MARK 1200 -#define SONY_ZERO_MARK 600 -#define SONY_RPT_LENGTH 45000 -#define SONY_DOUBLE_SPACE_USECS 500 // usually ssee 713 - not using ticks as get number wrapround - -//+============================================================================= -#if SEND_SONY -void IRsend::sendSony (unsigned long data, int nbits) -{ - // Set IR carrier frequency - enableIROut(40); - - // Header - mark(SONY_HDR_MARK); - space(SONY_HDR_SPACE); - - // Data - for (unsigned long mask = 1UL << (nbits - 1); mask; mask >>= 1) { - if (data & mask) { - mark(SONY_ONE_MARK); - space(SONY_HDR_SPACE); - } else { - mark(SONY_ZERO_MARK); - space(SONY_HDR_SPACE); - } - } - - // We will have ended with LED off -} -#endif - -//+============================================================================= -#if DECODE_SONY -bool IRrecv::decodeSony (decode_results *results) -{ - long data = 0; - int offset = 0; // Dont skip first space, check its size - - if (irparams.rawlen < (2 * SONY_BITS) + 2) return false ; - - // Some Sony's deliver repeats fast after first - // unfortunately can't spot difference from of repeat from two fast clicks - if (results->rawbuf[offset] < SONY_DOUBLE_SPACE_USECS) { - // Serial.print("IR Gap found: "); - results->bits = 0; - results->value = REPEAT; - -# ifdef DECODE_SANYO - results->decode_type = SANYO; -# else - results->decode_type = UNKNOWN; -# endif - - return true; - } - offset++; - - // Initial mark - if (!MATCH_MARK(results->rawbuf[offset++], SONY_HDR_MARK)) return false ; - - while (offset + 1 < irparams.rawlen) { - if (!MATCH_SPACE(results->rawbuf[offset++], SONY_HDR_SPACE)) break ; - - if (MATCH_MARK(results->rawbuf[offset], SONY_ONE_MARK)) data = (data << 1) | 1 ; - else if (MATCH_MARK(results->rawbuf[offset], SONY_ZERO_MARK)) data = (data << 1) | 0 ; - else return false ; - offset++; - } - - // Success - results->bits = (offset - 1) / 2; - if (results->bits < 12) { - results->bits = 0; - return false; - } - results->value = data; - results->decode_type = SONY; - return true; -} -#endif - diff --git a/lib/Arduino-IRremote/ir_Template.cpp b/lib/Arduino-IRremote/ir_Template.cpp deleted file mode 100644 index 09630c00..00000000 --- a/lib/Arduino-IRremote/ir_Template.cpp +++ /dev/null @@ -1,179 +0,0 @@ -/* -Assuming the protocol we are adding is for the (imaginary) manufacturer: Shuzu - -Our fantasy protocol is a standard protocol, so we can use this standard -template without too much work. Some protocols are quite unique and will require -considerably more work in this file! It is way beyond the scope of this text to -explain how to reverse engineer "unusual" IR protocols. But, unless you own an -oscilloscope, the starting point is probably to use the rawDump.ino sketch and -try to spot the pattern! - -Before you start, make sure the IR library is working OK: - # Open up the Arduino IDE - # Load up the rawDump.ino example sketch - # Run it - -Now we can start to add our new protocol... - -1. Copy this file to : ir_Shuzu.cpp - -2. Replace all occurrences of "Shuzu" with the name of your protocol. - -3. Tweak the #defines to suit your protocol. - -4. If you're lucky, tweaking the #defines will make the default send() function - work. - -5. Again, if you're lucky, tweaking the #defines will have made the default - decode() function work. - -You have written the code to support your new protocol! - -Now you must do a few things to add it to the IRremote system: - -1. Open IRremote.h and make the following changes: - REMEMEBER to change occurences of "SHUZU" with the name of your protocol - - A. At the top, in the section "Supported Protocols", add: - #define DECODE_SHUZU 1 - #define SEND_SHUZU 1 - - B. In the section "enumerated list of all supported formats", add: - SHUZU, - to the end of the list (notice there is a comma after the protocol name) - - C. Further down in "Main class for receiving IR", add: - //...................................................................... - #if DECODE_SHUZU - bool decodeShuzu (decode_results *results) ; - #endif - - D. Further down in "Main class for sending IR", add: - //...................................................................... - #if SEND_SHUZU - void sendShuzu (unsigned long data, int nbits) ; - #endif - - E. Save your changes and close the file - -2. Now open irRecv.cpp and make the following change: - - A. In the function IRrecv::decode(), add: - #ifdef DECODE_NEC - DBG_PRINTLN("Attempting Shuzu decode"); - if (decodeShuzu(results)) return true ; - #endif - - B. Save your changes and close the file - -You will probably want to add your new protocol to the example sketch - -3. Open MyDocuments\Arduino\libraries\IRremote\examples\IRrecvDumpV2.ino - - A. In the encoding() function, add: - case SHUZU: Serial.print("SHUZU"); break ; - -Now open the Arduino IDE, load up the rawDump.ino sketch, and run it. -Hopefully it will compile and upload. -If it doesn't, you've done something wrong. Check your work. -If you can't get it to work - seek help from somewhere. - -If you get this far, I will assume you have successfully added your new protocol -There is one last thing to do. - -1. Delete this giant instructional comment. - -2. Send a copy of your work to us so we can include it in the library and - others may benefit from your hard work and maybe even write a song about how - great you are for helping them! :) - -Regards, - BlueChip -*/ - -#include "IRremote.h" -#include "IRremoteInt.h" - -//============================================================================== -// -// -// S H U Z U -// -// -//============================================================================== - -#define BITS 32 // The number of bits in the command - -#define HDR_MARK 1000 // The length of the Header:Mark -#define HDR_SPACE 2000 // The lenght of the Header:Space - -#define BIT_MARK 3000 // The length of a Bit:Mark -#define ONE_SPACE 4000 // The length of a Bit:Space for 1's -#define ZERO_SPACE 5000 // The length of a Bit:Space for 0's - -#define OTHER 1234 // Other things you may need to define - -//+============================================================================= -// -#if SEND_SHUZU -void IRsend::sendShuzu (unsigned long data, int nbits) -{ - // Set IR carrier frequency - enableIROut(38); - - // Header - mark (HDR_MARK); - space(HDR_SPACE); - - // Data - for (unsigned long mask = 1UL << (nbits - 1); mask; mask >>= 1) { - if (data & mask) { - mark (BIT_MARK); - space(ONE_SPACE); - } else { - mark (BIT_MARK); - space(ZERO_SPACE); - } - } - - // Footer - mark(BIT_MARK); - space(0); // Always end with the LED off -} -#endif - -//+============================================================================= -// -#if DECODE_SHUZU -bool IRrecv::decodeShuzu (decode_results *results) -{ - unsigned long data = 0; // Somewhere to build our code - int offset = 1; // Skip the Gap reading - - // Check we have the right amount of data - if (irparams.rawlen != 1 + 2 + (2 * BITS) + 1) return false ; - - // Check initial Mark+Space match - if (!MATCH_MARK (results->rawbuf[offset++], HDR_MARK )) return false ; - if (!MATCH_SPACE(results->rawbuf[offset++], HDR_SPACE)) return false ; - - // Read the bits in - for (int i = 0; i < SHUZU_BITS; i++) { - // Each bit looks like: MARK + SPACE_1 -> 1 - // or : MARK + SPACE_0 -> 0 - if (!MATCH_MARK(results->rawbuf[offset++], BIT_MARK)) return false ; - - // IR data is big-endian, so we shuffle it in from the right: - if (MATCH_SPACE(results->rawbuf[offset], ONE_SPACE)) data = (data << 1) | 1 ; - else if (MATCH_SPACE(results->rawbuf[offset], ZERO_SPACE)) data = (data << 1) | 0 ; - else return false ; - offset++; - } - - // Success - results->bits = BITS; - results->value = data; - results->decode_type = SHUZU; - return true; -} -#endif diff --git a/lib/Arduino-IRremote/ir_Whynter.cpp b/lib/Arduino-IRremote/ir_Whynter.cpp deleted file mode 100644 index 8b7bf0e6..00000000 --- a/lib/Arduino-IRremote/ir_Whynter.cpp +++ /dev/null @@ -1,91 +0,0 @@ -#include "IRremote.h" -#include "IRremoteInt.h" - -//============================================================================== -// W W H H Y Y N N TTTTT EEEEE RRRRR -// W W H H Y Y NN N T E R R -// W W W HHHHH Y N N N T EEE RRRR -// W W W H H Y N NN T E R R -// WWW H H Y N N T EEEEE R R -//============================================================================== - -#define WHYNTER_BITS 32 -#define WHYNTER_HDR_MARK 2850 -#define WHYNTER_HDR_SPACE 2850 -#define WHYNTER_BIT_MARK 750 -#define WHYNTER_ONE_MARK 750 -#define WHYNTER_ONE_SPACE 2150 -#define WHYNTER_ZERO_MARK 750 -#define WHYNTER_ZERO_SPACE 750 - -//+============================================================================= -#if SEND_WHYNTER -void IRsend::sendWhynter (unsigned long data, int nbits) -{ - // Set IR carrier frequency - enableIROut(38); - - // Start - mark(WHYNTER_ZERO_MARK); - space(WHYNTER_ZERO_SPACE); - - // Header - mark(WHYNTER_HDR_MARK); - space(WHYNTER_HDR_SPACE); - - // Data - for (unsigned long mask = 1UL << (nbits - 1); mask; mask >>= 1) { - if (data & mask) { - mark(WHYNTER_ONE_MARK); - space(WHYNTER_ONE_SPACE); - } else { - mark(WHYNTER_ZERO_MARK); - space(WHYNTER_ZERO_SPACE); - } - } - - // Footer - mark(WHYNTER_ZERO_MARK); - space(WHYNTER_ZERO_SPACE); // Always end with the LED off -} -#endif - -//+============================================================================= -#if DECODE_WHYNTER -bool IRrecv::decodeWhynter (decode_results *results) -{ - long data = 0; - int offset = 1; // skip initial space - - // Check we have the right amount of data - if (irparams.rawlen < (2 * WHYNTER_BITS) + 6) return false ; - - // Sequence begins with a bit mark and a zero space - if (!MATCH_MARK (results->rawbuf[offset++], WHYNTER_BIT_MARK )) return false ; - if (!MATCH_SPACE(results->rawbuf[offset++], WHYNTER_ZERO_SPACE)) return false ; - - // header mark and space - if (!MATCH_MARK (results->rawbuf[offset++], WHYNTER_HDR_MARK )) return false ; - if (!MATCH_SPACE(results->rawbuf[offset++], WHYNTER_HDR_SPACE)) return false ; - - // data bits - for (int i = 0; i < WHYNTER_BITS; i++) { - if (!MATCH_MARK(results->rawbuf[offset++], WHYNTER_BIT_MARK)) return false ; - - if (MATCH_SPACE(results->rawbuf[offset], WHYNTER_ONE_SPACE )) data = (data << 1) | 1 ; - else if (MATCH_SPACE(results->rawbuf[offset], WHYNTER_ZERO_SPACE)) data = (data << 1) | 0 ; - else return false ; - offset++; - } - - // trailing mark - if (!MATCH_MARK(results->rawbuf[offset], WHYNTER_BIT_MARK)) return false ; - - // Success - results->bits = WHYNTER_BITS; - results->value = data; - results->decode_type = WHYNTER; - return true; -} -#endif - diff --git a/lib/Arduino-IRremote/keywords.txt b/lib/Arduino-IRremote/keywords.txt deleted file mode 100644 index f2b9a495..00000000 --- a/lib/Arduino-IRremote/keywords.txt +++ /dev/null @@ -1,53 +0,0 @@ -####################################### -# Syntax Coloring Map For IRremote -####################################### - -####################################### -# Datatypes (KEYWORD1) -####################################### - -decode_results KEYWORD1 -IRrecv KEYWORD1 -IRsend KEYWORD1 - -####################################### -# Methods and Functions (KEYWORD2) -####################################### - -blink13 KEYWORD2 -decode KEYWORD2 -enableIRIn KEYWORD2 -resume KEYWORD2 -enableIROut KEYWORD2 -sendNEC KEYWORD2 -sendSony KEYWORD2 -sendSanyo KEYWORD2 -sendMitsubishi KEYWORD2 -sendRaw KEYWORD2 -sendRC5 KEYWORD2 -sendRC6 KEYWORD2 -sendDISH KEYWORD2 -sendSharp KEYWORD2 -sendSharpRaw KEYWORD2 -sendPanasonic KEYWORD2 -sendJVC KEYWORD2 -sendLG KEYWORD2 - -####################################### -# Constants (LITERAL1) -####################################### - -NEC LITERAL1 -SONY LITERAL1 -SANYO LITERAL1 -MITSUBISHI LITERAL1 -RC5 LITERAL1 -RC6 LITERAL1 -DISH LITERAL1 -SHARP LITERAL1 -PANASONIC LITERAL1 -JVC LITERAL1 -LG LITERAL1 -AIWA_RC_T501 LITERAL1 -UNKNOWN LITERAL1 -REPEAT LITERAL1 diff --git a/lib/Arduino-IRremote/library.json b/lib/Arduino-IRremote/library.json deleted file mode 100644 index d8cd523a..00000000 --- a/lib/Arduino-IRremote/library.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "name": "IRremote", - "keywords": "infrared, ir, remote", - "description": "Send and receive infrared signals with multiple protocols", - "repository": - { - "type": "git", - "url": "https://github.com/z3t0/Arduino-IRremote.git" - }, - "version": "2.3.3", - "frameworks": "arduino", - "platforms": "atmelavr", - "authors" : - [ - { - "name":"Rafi Khan", - "email":"zetoslab@gmail.com" - }, - { - "name":"Ken Shirriff", - "email":"ken.shirriff@gmail.com" - } - ] -} diff --git a/lib/Arduino-IRremote/library.properties b/lib/Arduino-IRremote/library.properties deleted file mode 100644 index 39fd814e..00000000 --- a/lib/Arduino-IRremote/library.properties +++ /dev/null @@ -1,9 +0,0 @@ -name=IRremote -version=2.2.3 -author=shirriff -maintainer=shirriff -sentence=Send and receive infrared signals with multiple protocols -paragraph=Send and receive infrared signals with multiple protocols -category=Signal Input/Output -url=https://github.com/shirriff/Arduino-IRremote.git -architectures=* diff --git a/lib/ArduinoJson/ArduinoJson.h b/lib/ArduinoJson/ArduinoJson.h deleted file mode 100644 index 9f78b9f1..00000000 --- a/lib/ArduinoJson/ArduinoJson.h +++ /dev/null @@ -1,5 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#include "src/ArduinoJson.h" diff --git a/lib/ArduinoJson/CHANGELOG.md b/lib/ArduinoJson/CHANGELOG.md deleted file mode 100644 index dc5206f0..00000000 --- a/lib/ArduinoJson/CHANGELOG.md +++ /dev/null @@ -1,478 +0,0 @@ -ArduinoJson: change log -======================= - -v5.13.3 -------- - -* Improved float serialization when `-fsingle-precision-constant` is used -* Fixed `JsonVariant::is()` that returned true for empty strings -* Fixed `JsonVariant::is()` (closes #763) - -v5.13.2 -------- - -* Fixed `JsonBuffer::parse()` not respecting nesting limit correctly (issue #693) -* Fixed inconsistencies in nesting level counting (PR #695 from Zhenyu Wu) -* Fixed null values that could be pass to `strcmp()` (PR #745 from Mike Karlesky) -* Added macros `ARDUINOJSON_VERSION`, `ARDUINOJSON_VERSION_MAJOR`... - -v5.13.1 -------- - -* Fixed `JsonVariant::operator|(int)` that returned the default value if the variant contained a double (issue #675) -* Allowed non-quoted key to contain underscores (issue #665) - -v5.13.0 -------- - -* Changed the rules of string duplication (issue #658) -* `RawJson()` accepts any kind of string and obeys to the same rules for duplication -* Changed the return type of `strdup()` to `const char*` to prevent double duplication -* Marked `strdup()` as deprecated - -> ### New rules for string duplication -> -> | type | duplication | -> |:---------------------------|:------------| -> | const char* | no | -> | char* | ~~no~~ yes | -> | String | yes | -> | std::string | yes | -> | const __FlashStringHelper* | yes | -> -> These new rules make `JsonBuffer::strdup()` useless. - -v5.12.0 -------- - -* Added `JsonVariant::operator|` to return a default value (see below) -* Added a clear error message when compiled as C instead of C++ (issue #629) -* Added detection of MPLAB XC compiler (issue #629) -* Added detection of Keil ARM Compiler (issue #629) -* Added an example that shows how to save and load a configuration file -* Reworked all other examples - -> ### How to use the new feature? -> -> If you have a block like this: -> -> ```c++ -> const char* ssid = root["ssid"]; -> if (!ssid) -> ssid = "default ssid"; -> ``` -> -> You can simplify like that: -> -> ```c++ -> const char* ssid = root["ssid"] | "default ssid"; -> ``` - -v5.11.2 -------- - -* Fixed `DynamicJsonBuffer::clear()` not resetting allocation size (issue #561) -* Fixed incorrect rounding for float values (issue #588) - -v5.11.1 -------- - -* Removed dependency on `PGM_P` as Particle 0.6.2 doesn't define it (issue #546) -* Fixed warning "dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing]" -* Fixed warning "floating constant exceeds range of 'float' [-Woverflow]" (issue #544) -* Fixed warning "this statement may fall through" [-Wimplicit-fallthrough=] (issue #539) -* Removed `ARDUINOJSON_DOUBLE_IS_64BITS` as it became useless. -* Fixed too many decimals places in float serialization (issue #543) - -v5.11.0 -------- - -* Made `JsonBuffer` non-copyable (PR #524 by @luisrayas3) -* Added `StaticJsonBuffer::clear()` -* Added `DynamicJsonBuffer::clear()` - -v5.10.1 -------- - -* Fixed IntelliSense errors in Visual Micro (issue #483) -* Fixed compilation in IAR Embedded Workbench (issue #515) -* Fixed reading "true" as a float (issue #516) -* Added `ARDUINOJSON_DOUBLE_IS_64BITS` -* Added `ARDUINOJSON_EMBEDDED_MODE` - -v5.10.0 -------- - -* Removed configurable number of decimal places (issues #288, #427 and #506) -* Changed exponentiation thresholds to `1e7` and `1e-5` (issues #288, #427 and #506) -* `JsonVariant::is()` now returns `true` for integers -* Fixed error `IsBaseOf is not a member of ArduinoJson::TypeTraits` (issue #495) -* Fixed error `forming reference to reference` (issue #495) - -> ### BREAKING CHANGES :warning: -> -> | Old syntax | New syntax | -> |:--------------------------------|:--------------------| -> | `double_with_n_digits(3.14, 2)` | `3.14` | -> | `float_with_n_digits(3.14, 2)` | `3.14f` | -> | `obj.set("key", 3.14, 2)` | `obj["key"] = 3.14` | -> | `arr.add(3.14, 2)` | `arr.add(3.14)` | -> -> | Input | Old output | New output | -> |:----------|:-----------|:-----------| -> | `3.14159` | `3.14` | `3.14159` | -> | `42.0` | `42.00` | `42` | -> | `0.0` | `0.00` | `0` | -> -> | Expression | Old result | New result | -> |:-------------------------------|:-----------|:-----------| -> | `JsonVariant(42).is()` | `true` | `true` | -> | `JsonVariant(42).is()` | `false` | `true` | -> | `JsonVariant(42).is()` | `false` | `true` | - -v5.9.0 ------- - -* Added `JsonArray::remove(iterator)` (issue #479) -* Added `JsonObject::remove(iterator)` -* Renamed `JsonArray::removeAt(size_t)` into `remove(size_t)` -* Renamed folder `include/` to `src/` -* Fixed warnings `floating constant exceeds range of float`and `floating constant truncated to zero` (issue #483) -* Removed `Print` class and converted `printTo()` to a template method (issue #276) -* Removed example `IndentedPrintExample.ino` -* Now compatible with Particle 0.6.1, thanks to Jacob Nite (issue #294 and PR #461 by @foodbag) - -v5.8.4 ------- - -* Added custom implementation of `strtod()` (issue #453) -* Added custom implementation of `strtol()` (issue #465) -* `char` is now treated as an integral type (issue #337, #370) - -v5.8.3 ------- - -* Fixed an access violation in `DynamicJsonBuffer` when memory allocation fails (issue #433) -* Added operators `==` and `!=` for two `JsonVariant`s (issue #436) -* Fixed `JsonVariant::operator[const FlashStringHelper*]` (issue #441) - -v5.8.2 ------- - -* Fixed parsing of comments (issue #421) -* Fixed ignored `Stream` timeout (issue #422) -* Made sure we don't read more that necessary (issue #422) -* Fixed error when the key of a `JsonObject` is a `char[]` (issue #423) -* Reduced code size when using `const` references -* Fixed error with string of type `unsigned char*` (issue #428) -* Added `deprecated` attribute on `asArray()`, `asObject()` and `asString()` (issue #420) - -v5.8.1 ------- - -* Fixed error when assigning a `volatile int` to a `JsonVariant` (issue #415) -* Fixed errors with Variable Length Arrays (issue #416) -* Fixed error when both `ARDUINOJSON_ENABLE_STD_STREAM` and `ARDUINOJSON_ENABLE_ARDUINO_STREAM` are set to `1` -* Fixed error "Stream does not name a type" (issue #412) - -v5.8.0 ------- - -* Added operator `==` to compare `JsonVariant` and strings (issue #402) -* Added support for `Stream` (issue #300) -* Reduced memory consumption by not duplicating spaces and comments - -> ### BREAKING CHANGES :warning: -> -> `JsonBuffer::parseObject()` and `JsonBuffer::parseArray()` have been pulled down to the derived classes `DynamicJsonBuffer` and `StaticJsonBufferBase`. -> -> This means that if you have code like: -> -> ```c++ -> void myFunction(JsonBuffer& jsonBuffer); -> ``` -> -> you need to replace it with one of the following: -> -> ```c++ -> void myFunction(DynamicJsonBuffer& jsonBuffer); -> void myFunction(StaticJsonBufferBase& jsonBuffer); -> template void myFunction(TJsonBuffer& jsonBuffer); -> ``` - -v5.7.3 ------- - -* Added an `printTo(char[N])` and `prettyPrintTo(char[N])` (issue #292) -* Added ability to set a nested value like this: `root["A"]["B"] = "C"` (issue #352) -* Renamed `*.ipp` to `*Impl.hpp` because they were ignored by Arduino IDE (issue #396) - -v5.7.2 ------- - -* Made PROGMEM available on more platforms (issue #381) -* Fixed PROGMEM causing an exception on ESP8266 (issue #383) - -v5.7.1 ------- - -* Added support for PROGMEM (issue #76) -* Fixed compilation error when index is not an `int` (issue #381) - -v5.7.0 ------- - -* Templatized all functions using `String` or `std::string` -* Removed `ArduinoJson::String` -* Removed `JsonVariant::defaultValue()` -* Removed non-template `JsonObject::get()` and `JsonArray.get()` -* Fixed support for `StringSumHelper` (issue #184) -* Replaced `ARDUINOJSON_USE_ARDUINO_STRING` by `ARDUINOJSON_ENABLE_STD_STRING` and `ARDUINOJSON_ENABLE_ARDUINO_STRING` (issue #378) -* Added example `StringExample.ino` to show where `String` can be used -* Increased default nesting limit to 50 when compiled for a computer (issue #349) - -> ### BREAKING CHANGES :warning: -> -> The non-template functions `JsonObject::get()` and `JsonArray.get()` have been removed. This means that you need to explicitely tell the type you expect in return. -> -> Old code: -> -> ```c++ -> #define ARDUINOJSON_USE_ARDUINO_STRING 0 -> JsonVariant value1 = myObject.get("myKey"); -> JsonVariant value2 = myArray.get(0); -> ``` -> -> New code: -> -> ```c++ -> #define ARDUINOJSON_ENABLE_ARDUINO_STRING 0 -> #define ARDUINOJSON_ENABLE_STD_STRING 1 -> JsonVariant value1 = myObject.get("myKey"); -> JsonVariant value2 = myArray.get(0); -> ``` - -v5.6.7 ------- - -* Fixed `array[idx].as()` and `object[key].as()` -* Fixed return value of `JsonObject::set()` (issue #350) -* Fixed undefined behavior in `Prettyfier` and `Print` (issue #354) -* Fixed parser that incorrectly rejected floats containing a `+` (issue #349) - -v5.6.6 ------- - -* Fixed `-Wparentheses` warning introduced in v5.6.5 (PR #335 by @nuket) -* Added `.mbedignore` for ARM mbdeb (PR #334 by @nuket) -* Fixed `JsonVariant::success()` which didn't propagate `JsonArray::success()` nor `JsonObject::success()` (issue #342). - -v5.6.5 ------- - -* `as()` now returns `true` when input is `null` (issue #330) - -v5.6.4 ------- - -* Fixed error in float serialization (issue #324) - -v5.6.3 ------- - -* Improved speed of float serialization (about twice faster) -* Added `as()` as a synonym for `as()`... (issue #291) -* Fixed `call of overloaded isinf(double&) is ambiguous` (issue #284) - -v5.6.2 ------- - -* Fixed build when another lib does `#undef isnan` (issue #284) - -v5.6.1 ------- - -* Added missing `#pragma once` (issue #310) - -v5.6.0 ------- - -* ArduinoJson is now a header-only library (issue #199) - -v5.5.1 ------- - -* Fixed compilation error with Intel Galileo (issue #299) - -v5.5.0 ------- - -* Added `JsonVariant::success()` (issue #279) -* Renamed `JsonVariant::invalid()` to `JsonVariant::defaultValue()` - -v5.4.0 ------- - -* Changed `::String` to `ArduinoJson::String` (issue #275) -* Changed `::Print` to `ArduinoJson::Print` too - -v5.3.0 ------- - -* Added custom implementation of `ftoa` (issues #266, #267, #269 and #270) -* Added `JsonVariant JsonBuffer::parse()` (issue #265) -* Fixed `unsigned long` printed as `signed long` (issue #170) - -v5.2.0 ------- - -* Added `JsonVariant::as()` as a synonym for `JsonVariant::as()` (issue #257) -* Added example `JsonHttpClient` (issue #256) -* Added `JsonArray::copyTo()` and `JsonArray::copyFrom()` (issue #254) -* Added `RawJson()` to insert pregenerated JSON portions (issue #259) - -v5.1.1 ------- - -* Removed `String` duplication when one replaces a value in a `JsonObject` (PR #232 by @ulion) - -v5.1.0 ------- - -* Added support of `long long` (issue #171) -* Moved all build settings to `ArduinoJson/Configuration.hpp` - -> ### BREAKING CHANGE :warning: -> -> If you defined `ARDUINOJSON_ENABLE_STD_STREAM`, you now need to define it to `1`. - -v5.0.8 ------- - -* Made the library compatible with [PlatformIO](http://platformio.org/) (issue #181) -* Fixed `JsonVariant::is()` that was incorrectly returning false (issue #214) - -v5.0.7 ------- - -* Made library easier to use from a CMake project: simply `add_subdirectory(ArduinoJson/src)` -* Changed `String` to be a `typedef` of `std::string` (issues #142 and #161) - -> ### BREAKING CHANGES :warning: -> -> - `JsonVariant(true).as()` now returns `"true"` instead of `"1"` -> - `JsonVariant(false).as()` now returns `"false"` instead of `"0"` - -v5.0.6 ------- - -* Added parameter to `DynamicJsonBuffer` constructor to set initial size (issue #152) -* Fixed warning about library category in Arduino 1.6.6 (issue #147) -* Examples: Added a loop to wait for serial port to be ready (issue #156) - -v5.0.5 ------- - -* Added overload `JsonObjectSuscript::set(value, decimals)` (issue #143) -* Use `float` instead of `double` to reduce the size of `JsonVariant` (issue #134) - -v5.0.4 ------- - -* Fixed ambiguous overload with `JsonArraySubscript` and `JsonObjectSubscript` (issue #122) - -v5.0.3 ------- - -* Fixed `printTo(String)` which wrote numbers instead of strings (issue #120) -* Fixed return type of `JsonArray::is()` and some others (issue #121) - -v5.0.2 ------- - -* Fixed segmentation fault in `parseObject(String)` and `parseArray(String)`, when the - `StaticJsonBuffer` is too small to hold a copy of the string -* Fixed Clang warning "register specifier is deprecated" (issue #102) -* Fixed GCC warning "declaration shadows a member" (issue #103) -* Fixed memory alignment, which made ESP8266 crash (issue #104) -* Fixed compilation on Visual Studio 2010 and 2012 (issue #107) - -v5.0.1 ------- - -* Fixed compilation with Arduino 1.0.6 (issue #99) - -v5.0.0 ------- - -* Added support of `String` class (issues #55, #56, #70, #77) -* Added `JsonBuffer::strdup()` to make a copy of a string (issues #10, #57) -* Implicitly call `strdup()` for `String` but not for `char*` (issues #84, #87) -* Added support of non standard JSON input (issue #44) -* Added support of comments in JSON input (issue #88) -* Added implicit cast between numerical types (issues #64, #69, #93) -* Added ability to read number values as string (issue #90) -* Redesigned `JsonVariant` to leverage converting constructors instead of assignment operators (issue #66) -* Switched to new the library layout (requires Arduino 1.0.6 or above) - -> ### BREAKING CHANGES :warning: -> -> - `JsonObject::add()` was renamed to `set()` -> - `JsonArray::at()` and `JsonObject::at()` were renamed to `get()` -> - Number of digits of floating point value are now set with `double_with_n_digits()` - -**Personal note about the `String` class**: -Support of the `String` class has been added to the library because many people use it in their programs. -However, you should not see this as an invitation to use the `String` class. -The `String` class is **bad** because it uses dynamic memory allocation. -Compared to static allocation, it compiles to a bigger, slower program, and is less predictable. -You certainly don't want that in an embedded environment! - -v4.6 ----- - -* Fixed segmentation fault in `DynamicJsonBuffer` when memory allocation fails (issue #92) - -v4.5 ----- - -* Fixed buffer overflow when input contains a backslash followed by a terminator (issue #81) - -**Upgrading is recommended** since previous versions contain a potential security risk. - -Special thanks to [Giancarlo Canales Barreto](https://github.com/gcanalesb) for finding this nasty bug. - -v4.4 ----- - -* Added `JsonArray::measureLength()` and `JsonObject::measureLength()` (issue #75) - -v4.3 ----- - -* Added `JsonArray::removeAt()` to remove an element of an array (issue #58) -* Fixed stack-overflow in `DynamicJsonBuffer` when parsing huge JSON files (issue #65) -* Fixed wrong return value of `parseArray()` and `parseObject()` when allocation fails (issue #68) - -v4.2 ----- - -* Switched back to old library layout (issues #39, #43 and #45) -* Removed global new operator overload (issue #40, #45 and #46) -* Added an example with EthernetServer - -v4.1 ----- - -* Added DynamicJsonBuffer (issue #19) - -v4.0 ----- - -* Unified parser and generator API (issue #23) -* Updated library layout, now requires Arduino 1.0.6 or newer - -> ### BREAKING CHANGES :warning: -> -> API changed significantly since v3, see [Migrating code to the new API](https://arduinojson.org/doc/migration/). - diff --git a/lib/ArduinoJson/LICENSE.md b/lib/ArduinoJson/LICENSE.md deleted file mode 100644 index f0c4b5ae..00000000 --- a/lib/ArduinoJson/LICENSE.md +++ /dev/null @@ -1,10 +0,0 @@ -The MIT License (MIT) ---------------------- - -Copyright © 2014-2018 Benoit BLANCHON - -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. diff --git a/lib/ArduinoJson/README.md b/lib/ArduinoJson/README.md deleted file mode 100644 index 8ddc698f..00000000 --- a/lib/ArduinoJson/README.md +++ /dev/null @@ -1,110 +0,0 @@ -![ArduinoJson](banner.svg) - ---- - -[![Build status](https://ci.appveyor.com/api/projects/status/m7s53wav1l0abssg/branch/master?svg=true)](https://ci.appveyor.com/project/bblanchon/arduinojson/branch/master) [![Build Status](https://travis-ci.org/bblanchon/ArduinoJson.svg?branch=master)](https://travis-ci.org/bblanchon/ArduinoJson) [![Coverage Status](https://img.shields.io/coveralls/bblanchon/ArduinoJson.svg)](https://coveralls.io/r/bblanchon/ArduinoJson?branch=master) [![Star this project](http://githubbadges.com/star.svg?user=bblanchon&repo=ArduinoJson&style=flat&color=fff&background=007ec6)](https://github.com/bblanchon/ArduinoJson) - -ArduinoJson is a C++ JSON library for Arduino and IoT (Internet Of Things). - -## Features - -* JSON decoding (comments are supported) -* JSON encoding (with optional indentation) -* Elegant API, easy to use -* Fixed memory allocation (zero malloc) -* No data duplication (zero copy) -* Portable (written in C++98, can be used in any C++ project) -* Self-contained (no external dependency) -* Small footprint -* Input and output streams -* [100% code coverage](https://coveralls.io/github/bblanchon/ArduinoJson) -* [Header-only library](https://en.wikipedia.org/wiki/Header-only) -* [MIT License](https://en.wikipedia.org/wiki/MIT_License) -* [Comprehensive documentation](https://arduinojson.org?utm_source=github&utm_medium=readme) - -## Compatibility - -ArduinoJson works on the following hardware: - -* Arduino boards: [Uno](https://www.arduino.cc/en/Main/ArduinoBoardUno), [Due](https://www.arduino.cc/en/Main/ArduinoBoardDue), [Mini](https://www.arduino.cc/en/Main/ArduinoBoardMini), [Micro](https://www.arduino.cc/en/Main/ArduinoBoardMicro), [Yun](https://www.arduino.cc/en/Main/ArduinoBoardYun)... -* Espressif chips: [ESP8266](https://en.wikipedia.org/wiki/ESP8266), [ESP32](https://en.wikipedia.org/wiki/ESP32) -* WeMos boards: [D1](https://wiki.wemos.cc/products:d1:d1), [D1 mini](https://wiki.wemos.cc/products:d1:d1_mini), ... -* RedBearLab boards: [BLE Nano](http://redbearlab.com/blenano/), [BLE Mini](http://redbearlab.com/blemini/), [WiFi Micro](https://redbear.cc/product/wifi/wifi-micro.html), [LOLIN32](https://wiki.wemos.cc/products:lolin32:lolin32)... -* [Teensy](https://www.pjrc.com/teensy/) boards -* Intel boards: Edison, Galileo... -* Particle boards: [Photon](https://www.particle.io/products/hardware/photon-wifi-dev-kit), [Electron](https://www.particle.io/products/hardware/electron-cellular-dev-kit)... -* Texas Instruments boards: [MSP430](http://www.ti.com/microcontrollers/msp430-ultra-low-power-mcus/overview/overview.html)... - -ArduinoJson compiles with zero warning on the following compilers, IDEs, and platforms: - -* [Arduino IDE](https://www.arduino.cc/en/Main/Software) -* [PlatformIO](http://platformio.org/) -* [Energia](http://energia.nu/) -* [Visual Micro](http://www.visualmicro.com/) -* [Atmel Studio](http://www.atmel.com/microsite/atmel-studio/) -* [IAR Embedded Workbench](https://www.iar.com/iar-embedded-workbench/) -* [Atollic TrueSTUDIO](https://atollic.com/truestudio/) -* [Keil uVision](http://www.keil.com/) -* [MPLAB X IDE](http://www.microchip.com/mplab/mplab-x-ide) -* [GCC](https://gcc.gnu.org/) -* [Clang](https://clang.llvm.org/) -* [Visual Studio](https://www.visualstudio.com/) - -## Quickstart - -### Deserialization - -Here is a program that parses a JSON document with ArduinoJson. - -```c++ -char json[] = "{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}"; - -StaticJsonBuffer<200> jsonBuffer; - -JsonObject& root = jsonBuffer.parseObject(json); - -const char* sensor = root["sensor"]; -long time = root["time"]; -double latitude = root["data"][0]; -double longitude = root["data"][1]; -``` - -See the [tutorial on arduinojson.org](https://arduinojson.org/doc/decoding/?utm_source=github&utm_medium=readme) - -### Serialization - -Here is a program that generates a JSON document with ArduinoJson: - -```c++ -StaticJsonBuffer<200> jsonBuffer; - -JsonObject& root = jsonBuffer.createObject(); -root["sensor"] = "gps"; -root["time"] = 1351824120; - -JsonArray& data = root.createNestedArray("data"); -data.add(48.756080); -data.add(2.302038); - -root.printTo(Serial); -// This prints: -// {"sensor":"gps","time":1351824120,"data":[48.756080,2.302038]} -``` - -See the [tutorial on arduinojson.org](https://arduinojson.org/doc/encoding/?utm_source=github&utm_medium=readme) - -## Documentation - -The documentation is available on [arduinojson.org](https://arduinojson.org/?utm_source=github&utm_medium=readme), here are some shortcuts: - -* The [Examples](https://arduinojson.org/example/?utm_source=github&utm_medium=readme) show how to use the library in various situations. -* The [API Reference](https://arduinojson.org/api/?utm_source=github&utm_medium=readme) contains the description of each class and function. -* The [FAQ](https://arduinojson.org/faq/?utm_source=github&utm_medium=readme) has the answer to virtually every question. -* The [ArduinoJson Assistant](https://arduinojson.org/assistant/?utm_source=github&utm_medium=readme) writes programs for you! - ---- - -Do you like this library? Please [star this project on GitHub](https://github.com/bblanchon/ArduinoJson/stargazers)! - -What? You don't like it but you *love* it? -We don't take donations anymore, but [we sell a book](https://arduinojson.org/book/?utm_source=github&utm_medium=readme), so you can help and learn at the same time! \ No newline at end of file diff --git a/lib/ArduinoJson/examples/JsonConfigFile/JsonConfigFile.ino b/lib/ArduinoJson/examples/JsonConfigFile/JsonConfigFile.ino deleted file mode 100644 index 2ccf7d67..00000000 --- a/lib/ArduinoJson/examples/JsonConfigFile/JsonConfigFile.ino +++ /dev/null @@ -1,144 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License -// -// This example shows how to store your project configuration in a file. -// It uses the SD library but can be easily modified for any other file-system. -// -// The file contains a JSON document with the following content: -// { -// "hostname": "examples.com", -// "port": 2731 -// } - -#include -#include -#include - -// Configuration that we'll store on disk -struct Config { - char hostname[64]; - int port; -}; - -const char *filename = "/config.txt"; // <- SD library uses 8.3 filenames -Config config; // <- global configuration object - -// Loads the configuration from a file -void loadConfiguration(const char *filename, Config &config) { - // Open file for reading - File file = SD.open(filename); - - // Allocate the memory pool on the stack. - // Don't forget to change the capacity to match your JSON document. - // Use arduinojson.org/assistant to compute the capacity. - StaticJsonBuffer<512> jsonBuffer; - - // Parse the root object - JsonObject &root = jsonBuffer.parseObject(file); - - if (!root.success()) - Serial.println(F("Failed to read file, using default configuration")); - - // Copy values from the JsonObject to the Config - config.port = root["port"] | 2731; - strlcpy(config.hostname, // <- destination - root["hostname"] | "example.com", // <- source - sizeof(config.hostname)); // <- destination's capacity - - // Close the file (File's destructor doesn't close the file) - file.close(); -} - -// Saves the configuration to a file -void saveConfiguration(const char *filename, const Config &config) { - // Delete existing file, otherwise the configuration is appended to the file - SD.remove(filename); - - // Open file for writing - File file = SD.open(filename, FILE_WRITE); - if (!file) { - Serial.println(F("Failed to create file")); - return; - } - - // Allocate the memory pool on the stack - // Don't forget to change the capacity to match your JSON document. - // Use https://arduinojson.org/assistant/ to compute the capacity. - StaticJsonBuffer<256> jsonBuffer; - - // Parse the root object - JsonObject &root = jsonBuffer.createObject(); - - // Set the values - root["hostname"] = config.hostname; - root["port"] = config.port; - - // Serialize JSON to file - if (root.printTo(file) == 0) { - Serial.println(F("Failed to write to file")); - } - - // Close the file (File's destructor doesn't close the file) - file.close(); -} - -// Prints the content of a file to the Serial -void printFile(const char *filename) { - // Open file for reading - File file = SD.open(filename); - if (!file) { - Serial.println(F("Failed to read file")); - return; - } - - // Extract each characters by one by one - while (file.available()) { - Serial.print((char)file.read()); - } - Serial.println(); - - // Close the file (File's destructor doesn't close the file) - file.close(); -} - -void setup() { - // Initialize serial port - Serial.begin(9600); - while (!Serial) continue; - - // Initialize SD library - while (!SD.begin()) { - Serial.println(F("Failed to initialize SD library")); - delay(1000); - } - - // Should load default config if run for the first time - Serial.println(F("Loading configuration...")); - loadConfiguration(filename, config); - - // Create configuration file - Serial.println(F("Saving configuration...")); - saveConfiguration(filename, config); - - // Dump config file - Serial.println(F("Print config file...")); - printFile(filename); -} - -void loop() { - // not used in this example -} - -// See also -// -------- -// -// https://arduinojson.org/ contains the documentation for all the functions -// used above. It also includes an FAQ that will help you solve any -// serialization or deserialization problem. -// -// The book "Mastering ArduinoJson" contains a case study of a project that has -// a complex configuration with nested members. -// Contrary to this example, the project in the book uses the SPIFFS filesystem. -// Learn more at https://arduinojson.org/book/ -// Use the coupon code TWENTY for a 20% discount â¤â¤â¤â¤â¤ diff --git a/lib/ArduinoJson/examples/JsonGeneratorExample/JsonGeneratorExample.ino b/lib/ArduinoJson/examples/JsonGeneratorExample/JsonGeneratorExample.ino deleted file mode 100644 index 7b38227b..00000000 --- a/lib/ArduinoJson/examples/JsonGeneratorExample/JsonGeneratorExample.ino +++ /dev/null @@ -1,81 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License -// -// This example shows how to generate a JSON document with ArduinoJson. - -#include - -void setup() { - // Initialize Serial port - Serial.begin(9600); - while (!Serial) continue; - - // Memory pool for JSON object tree. - // - // Inside the brackets, 200 is the size of the pool in bytes. - // Don't forget to change this value to match your JSON document. - // Use arduinojson.org/assistant to compute the capacity. - StaticJsonBuffer<200> jsonBuffer; - - // StaticJsonBuffer allocates memory on the stack, it can be - // replaced by DynamicJsonBuffer which allocates in the heap. - // - // DynamicJsonBuffer jsonBuffer(200); - - // Create the root of the object tree. - // - // It's a reference to the JsonObject, the actual bytes are inside the - // JsonBuffer with all the other nodes of the object tree. - // Memory is freed when jsonBuffer goes out of scope. - JsonObject& root = jsonBuffer.createObject(); - - // Add values in the object - // - // Most of the time, you can rely on the implicit casts. - // In other case, you can do root.set("time", 1351824120); - root["sensor"] = "gps"; - root["time"] = 1351824120; - - // Add a nested array. - // - // It's also possible to create the array separately and add it to the - // JsonObject but it's less efficient. - JsonArray& data = root.createNestedArray("data"); - data.add(48.756080); - data.add(2.302038); - - root.printTo(Serial); - // This prints: - // {"sensor":"gps","time":1351824120,"data":[48.756080,2.302038]} - - Serial.println(); - - root.prettyPrintTo(Serial); - // This prints: - // { - // "sensor": "gps", - // "time": 1351824120, - // "data": [ - // 48.756080, - // 2.302038 - // ] - // } -} - -void loop() { - // not used in this example -} - -// See also -// -------- -// -// https://arduinojson.org/ contains the documentation for all the functions -// used above. It also includes an FAQ that will help you solve any -// serialization problem. -// -// The book "Mastering ArduinoJson" contains a tutorial on serialization. -// It begins with a simple example, like the one above, and then adds more -// features like serializing directly to a file or an HTTP request. -// Learn more at https://arduinojson.org/book/ -// Use the coupon code TWENTY for a 20% discount â¤â¤â¤â¤â¤ diff --git a/lib/ArduinoJson/examples/JsonHttpClient/JsonHttpClient.ino b/lib/ArduinoJson/examples/JsonHttpClient/JsonHttpClient.ino deleted file mode 100644 index 4ce1c20d..00000000 --- a/lib/ArduinoJson/examples/JsonHttpClient/JsonHttpClient.ino +++ /dev/null @@ -1,112 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License -// -// This example shows how to parse a JSON document in an HTTP response. -// It uses the Ethernet library, but can be easily adapted for Wifi. -// -// It performs a GET resquest on arduinojson.org/example.json -// Here is the expected response: -// { -// "sensor": "gps", -// "time": 1351824120, -// "data": [ -// 48.756080, -// 2.302038 -// ] -// } - -#include -#include -#include - -void setup() { - // Initialize Serial port - Serial.begin(9600); - while (!Serial) continue; - - // Initialize Ethernet library - byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; - if (!Ethernet.begin(mac)) { - Serial.println(F("Failed to configure Ethernet")); - return; - } - delay(1000); - - Serial.println(F("Connecting...")); - - // Connect to HTTP server - EthernetClient client; - client.setTimeout(10000); - if (!client.connect("arduinojson.org", 80)) { - Serial.println(F("Connection failed")); - return; - } - - Serial.println(F("Connected!")); - - // Send HTTP request - client.println(F("GET /example.json HTTP/1.0")); - client.println(F("Host: arduinojson.org")); - client.println(F("Connection: close")); - if (client.println() == 0) { - Serial.println(F("Failed to send request")); - return; - } - - // Check HTTP status - char status[32] = {0}; - client.readBytesUntil('\r', status, sizeof(status)); - if (strcmp(status, "HTTP/1.1 200 OK") != 0) { - Serial.print(F("Unexpected response: ")); - Serial.println(status); - return; - } - - // Skip HTTP headers - char endOfHeaders[] = "\r\n\r\n"; - if (!client.find(endOfHeaders)) { - Serial.println(F("Invalid response")); - return; - } - - // Allocate JsonBuffer - // Use arduinojson.org/assistant to compute the capacity. - const size_t capacity = JSON_OBJECT_SIZE(3) + JSON_ARRAY_SIZE(2) + 60; - DynamicJsonBuffer jsonBuffer(capacity); - - // Parse JSON object - JsonObject& root = jsonBuffer.parseObject(client); - if (!root.success()) { - Serial.println(F("Parsing failed!")); - return; - } - - // Extract values - Serial.println(F("Response:")); - Serial.println(root["sensor"].as()); - Serial.println(root["time"].as()); - Serial.println(root["data"][0].as()); - Serial.println(root["data"][1].as()); - - // Disconnect - client.stop(); -} - -void loop() { - // not used in this example -} - -// See also -// -------- -// -// https://arduinojson.org/ contains the documentation for all the functions -// used above. It also includes an FAQ that will help you solve any -// serialization problem. -// -// The book "Mastering ArduinoJson" contains a tutorial on deserialization -// showing how to parse the response from Yahoo Weather. In the last chapter, -// it shows how to parse the huge documents from OpenWeatherMap -// and Weather Underground. -// Learn more at https://arduinojson.org/book/ -// Use the coupon code TWENTY for a 20% discount â¤â¤â¤â¤â¤ diff --git a/lib/ArduinoJson/examples/JsonParserExample/JsonParserExample.ino b/lib/ArduinoJson/examples/JsonParserExample/JsonParserExample.ino deleted file mode 100644 index 6c16211b..00000000 --- a/lib/ArduinoJson/examples/JsonParserExample/JsonParserExample.ino +++ /dev/null @@ -1,78 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License -// -// This example shows how to deserialize a JSON document with ArduinoJson. - -#include - -void setup() { - // Initialize serial port - Serial.begin(9600); - while (!Serial) continue; - - // Memory pool for JSON object tree. - // - // Inside the brackets, 200 is the size of the pool in bytes. - // Don't forget to change this value to match your JSON document. - // Use arduinojson.org/assistant to compute the capacity. - StaticJsonBuffer<200> jsonBuffer; - - // StaticJsonBuffer allocates memory on the stack, it can be - // replaced by DynamicJsonBuffer which allocates in the heap. - // - // DynamicJsonBuffer jsonBuffer(200); - - // JSON input string. - // - // It's better to use a char[] as shown here. - // If you use a const char* or a String, ArduinoJson will - // have to make a copy of the input in the JsonBuffer. - char json[] = - "{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}"; - - // Root of the object tree. - // - // It's a reference to the JsonObject, the actual bytes are inside the - // JsonBuffer with all the other nodes of the object tree. - // Memory is freed when jsonBuffer goes out of scope. - JsonObject& root = jsonBuffer.parseObject(json); - - // Test if parsing succeeds. - if (!root.success()) { - Serial.println("parseObject() failed"); - return; - } - - // Fetch values. - // - // Most of the time, you can rely on the implicit casts. - // In other case, you can do root["time"].as(); - const char* sensor = root["sensor"]; - long time = root["time"]; - double latitude = root["data"][0]; - double longitude = root["data"][1]; - - // Print values. - Serial.println(sensor); - Serial.println(time); - Serial.println(latitude, 6); - Serial.println(longitude, 6); -} - -void loop() { - // not used in this example -} - -// See also -// -------- -// -// https://arduinojson.org/ contains the documentation for all the functions -// used above. It also includes an FAQ that will help you solve any -// deserialization problem. -// -// The book "Mastering ArduinoJson" contains a tutorial on deserialization. -// It begins with a simple example, like the one above, and then adds more -// features like deserializing directly from a file or an HTTP request. -// Learn more at https://arduinojson.org/book/ -// Use the coupon code TWENTY for a 20% discount â¤â¤â¤â¤â¤ diff --git a/lib/ArduinoJson/examples/JsonServer/JsonServer.ino b/lib/ArduinoJson/examples/JsonServer/JsonServer.ino deleted file mode 100644 index e693ae17..00000000 --- a/lib/ArduinoJson/examples/JsonServer/JsonServer.ino +++ /dev/null @@ -1,109 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License -// -// This example shows how to implement an HTTP server that sends JSON document -// in the responses. -// It uses the Ethernet library but can be easily adapted for Wifi. -// -// It sends the value of the analog and digital pins. -// The JSON document looks like the following: -// { -// "analog": [ 0, 1, 2, 3, 4, 5 ], -// "digital": [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 ] -// } - -#include -#include -#include - -byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; -EthernetServer server(80); - -void setup() { - // Initialize serial port - Serial.begin(9600); - while (!Serial) continue; - - // Initialize Ethernet libary - if (!Ethernet.begin(mac)) { - Serial.println(F("Failed to initialize Ethernet library")); - return; - } - - // Start to listen - server.begin(); - - Serial.println(F("Server is ready.")); - Serial.print(F("Please connect to http://")); - Serial.println(Ethernet.localIP()); -} - -void loop() { - // Wait for an incomming connection - EthernetClient client = server.available(); - - // Do we have a client? - if (!client) return; - - Serial.println(F("New client")); - - // Read the request (we ignore the content in this example) - while (client.available()) client.read(); - - // Allocate JsonBuffer - // Use arduinojson.org/assistant to compute the capacity. - StaticJsonBuffer<500> jsonBuffer; - - // Create the root object - JsonObject& root = jsonBuffer.createObject(); - - // Create the "analog" array - JsonArray& analogValues = root.createNestedArray("analog"); - for (int pin = 0; pin < 6; pin++) { - // Read the analog input - int value = analogRead(pin); - - // Add the value at the end of the array - analogValues.add(value); - } - - // Create the "digital" array - JsonArray& digitalValues = root.createNestedArray("digital"); - for (int pin = 0; pin < 14; pin++) { - // Read the digital input - int value = digitalRead(pin); - - // Add the value at the end of the array - digitalValues.add(value); - } - - Serial.print(F("Sending: ")); - root.printTo(Serial); - Serial.println(); - - // Write response headers - client.println("HTTP/1.0 200 OK"); - client.println("Content-Type: application/json"); - client.println("Connection: close"); - client.println(); - - // Write JSON document - root.prettyPrintTo(client); - - // Disconnect - client.stop(); -} - -// See also -// -------- -// -// https://arduinojson.org/ contains the documentation for all the functions -// used above. It also includes an FAQ that will help you solve any -// serialization problem. -// -// The book "Mastering ArduinoJson" contains a tutorial on serialization. -// It begins with a simple example, then adds more features like serializing -// directly to a file or an HTTP client. -// Learn more at https://arduinojson.org/book/ -// Use the coupon code TWENTY for a 20% discount â¤â¤â¤â¤â¤ diff --git a/lib/ArduinoJson/examples/JsonUdpBeacon/JsonUdpBeacon.ino b/lib/ArduinoJson/examples/JsonUdpBeacon/JsonUdpBeacon.ino deleted file mode 100644 index b2328a62..00000000 --- a/lib/ArduinoJson/examples/JsonUdpBeacon/JsonUdpBeacon.ino +++ /dev/null @@ -1,101 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License -// -// This example shows how to send a JSON document to a UDP socket. -// At regular interval, it sends a UDP packet that contains the status of -// analog and digital pins. -// The JSON document looks like the following: -// { -// "analog": [ 0, 1, 2, 3, 4, 5 ], -// "digital": [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 ] -// } -// -// If you want to test this program, you need to be able to receive the UDP -// packets. -// For example, you can run netcat on your computer -// $ ncat -ulp 8888 -// See https://nmap.org/ncat/ - -#include -#include -#include - -byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; -IPAddress remoteIp(192, 168, 0, 108); // <- EDIT!!!! -unsigned short remotePort = 8888; -unsigned short localPort = 8888; -EthernetUDP udp; - -void setup() { - // Initialize serial port - Serial.begin(9600); - while (!Serial) continue; - - // Initialize Ethernet libary - if (!Ethernet.begin(mac)) { - Serial.println(F("Failed to initialize Ethernet library")); - return; - } - - // Enable UDP - udp.begin(localPort); -} - -void loop() { - // Allocate JsonBuffer - // Use arduinojson.org/assistant to compute the capacity. - StaticJsonBuffer<500> jsonBuffer; - - // Create the root object - JsonObject& root = jsonBuffer.createObject(); - - // Create the "analog" array - JsonArray& analogValues = root.createNestedArray("analog"); - for (int pin = 0; pin < 6; pin++) { - // Read the analog input - int value = analogRead(pin); - - // Add the value at the end of the array - analogValues.add(value); - } - - // Create the "digital" array - JsonArray& digitalValues = root.createNestedArray("digital"); - for (int pin = 0; pin < 14; pin++) { - // Read the digital input - int value = digitalRead(pin); - - // Add the value at the end of the array - digitalValues.add(value); - } - - // Log - Serial.print(F("Sending to ")); - Serial.print(remoteIp); - Serial.print(F(" on port ")); - Serial.println(remotePort); - root.printTo(Serial); - - // Send UDP packet - udp.beginPacket(remoteIp, remotePort); - root.printTo(udp); - udp.println(); - udp.endPacket(); - - // Wait - delay(10000); -} - -// See also -// -------- -// -// https://arduinojson.org/ contains the documentation for all the functions -// used above. It also includes an FAQ that will help you solve any -// serialization problem. -// -// The book "Mastering ArduinoJson" contains a tutorial on serialization. -// It begins with a simple example, then adds more features like serializing -// directly to a file or any stream. -// Learn more at https://arduinojson.org/book/ -// Use the coupon code TWENTY for a 20% discount â¤â¤â¤â¤â¤ diff --git a/lib/ArduinoJson/examples/ProgmemExample/ProgmemExample.ino b/lib/ArduinoJson/examples/ProgmemExample/ProgmemExample.ino deleted file mode 100644 index ddde8fd1..00000000 --- a/lib/ArduinoJson/examples/ProgmemExample/ProgmemExample.ino +++ /dev/null @@ -1,70 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License -// -// This example shows the different ways you can use Flash strings with -// ArduinoJson. -// -// Use Flash strings sparingly, because ArduinoJson duplicates them in the -// JsonBuffer. Prefer plain old char*, as they are more efficient in term of -// code size, speed, and memory usage. - -#include - -void setup() { -#ifdef PROGMEM // <- check that Flash strings are supported - - DynamicJsonBuffer jsonBuffer; - - // You can use a Flash String as your JSON input. - // WARNING: the content of the Flash String will be duplicated in the - // JsonBuffer. - JsonObject& root = - jsonBuffer.parseObject(F("{\"sensor\":\"gps\",\"time\":1351824120," - "\"data\":[48.756080,2.302038]}")); - - // You can use a Flash String to get an element of a JsonObject - // No duplication is done. - long time = root[F("time")]; - - // You can use a Flash String to set an element of a JsonObject - // WARNING: the content of the Flash String will be duplicated in the - // JsonBuffer. - root[F("time")] = time; - - // You can set a Flash String to a JsonObject or JsonArray: - // WARNING: the content of the Flash String will be duplicated in the - // JsonBuffer. - root["sensor"] = F("gps"); - - // It works with RawJson too: - root["sensor"] = RawJson(F("\"gps\"")); - - // You can compare the content of a JsonVariant to a Flash String - if (root["sensor"] == F("gps")) { - // ... - } - -#else - -#warning PROGMEM is not supported on this platform - -#endif -} - -void loop() { - // not used in this example -} - -// See also -// -------- -// -// https://arduinojson.org/ contains the documentation for all the functions -// used above. It also includes an FAQ that will help you solve any memory -// problem. -// -// The book "Mastering ArduinoJson" contains a quick C++ course that explains -// how your microcontroller stores strings in memory. It also tells why you -// should not abuse Flash strings with ArduinoJson. -// Learn more at https://arduinojson.org/book/ -// Use the coupon code TWENTY for a 20% discount â¤â¤â¤â¤â¤ diff --git a/lib/ArduinoJson/examples/StringExample/StringExample.ino b/lib/ArduinoJson/examples/StringExample/StringExample.ino deleted file mode 100644 index fc7503d0..00000000 --- a/lib/ArduinoJson/examples/StringExample/StringExample.ino +++ /dev/null @@ -1,74 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License -// -// This example shows the different ways you can use String with ArduinoJson. -// -// Use String objects sparingly, because ArduinoJson duplicates them in the -// JsonBuffer. Prefer plain old char[], as they are more efficient in term of -// code size, speed, and memory usage. - -#include - -void setup() { - DynamicJsonBuffer jsonBuffer; - - // You can use a String as your JSON input. - // WARNING: the content of the String will be duplicated in the JsonBuffer. - String input = - "{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}"; - JsonObject& root = jsonBuffer.parseObject(input); - - // You can use a String to get an element of a JsonObject - // No duplication is done. - long time = root[String("time")]; - - // You can use a String to set an element of a JsonObject - // WARNING: the content of the String will be duplicated in the JsonBuffer. - root[String("time")] = time; - - // You can get a String from a JsonObject or JsonArray: - // No duplication is done, at least not in the JsonBuffer. - String sensor = root["sensor"]; - - // Unfortunately, the following doesn't work (issue #118): - // sensor = root["sensor"]; // <- error "ambiguous overload for 'operator='" - // As a workaround, you need to replace by: - sensor = root["sensor"].as(); - - // You can set a String to a JsonObject or JsonArray: - // WARNING: the content of the String will be duplicated in the JsonBuffer. - root["sensor"] = sensor; - - // It works with RawJson too: - root["sensor"] = RawJson(sensor); - - // You can also concatenate strings - // WARNING: the content of the String will be duplicated in the JsonBuffer. - root[String("sen") + "sor"] = String("gp") + "s"; - - // You can compare the content of a JsonObject with a String - if (root["sensor"] == sensor) { - // ... - } - - // Lastly, you can print the resulting JSON to a String - String output; - root.printTo(output); -} - -void loop() { - // not used in this example -} - -// See also -// -------- -// -// https://arduinojson.org/ contains the documentation for all the functions -// used above. It also includes an FAQ that will help you solve any problem. -// -// The book "Mastering ArduinoJson" contains a quick C++ course that explains -// how your microcontroller stores strings in memory. On several occasions, it -// shows how you can avoid String in your program. -// Learn more at https://arduinojson.org/book/ -// Use the coupon code TWENTY for a 20% discount â¤â¤â¤â¤â¤ diff --git a/lib/ArduinoJson/keywords.txt b/lib/ArduinoJson/keywords.txt deleted file mode 100644 index 833cddb7..00000000 --- a/lib/ArduinoJson/keywords.txt +++ /dev/null @@ -1,15 +0,0 @@ -JsonArray KEYWORD1 -JsonObject KEYWORD1 -JsonVariant KEYWORD1 -StaticJsonBuffer KEYWORD1 -DynamicJsonBuffer KEYWORD1 -add KEYWORD2 -createArray KEYWORD2 -createNestedArray KEYWORD2 -createNestedObject KEYWORD2 -createObject KEYWORD2 -parseArray KEYWORD2 -parseObject KEYWORD2 -prettyPrintTo KEYWORD2 -printTo KEYWORD2 -success KEYWORD2 diff --git a/lib/ArduinoJson/library.properties b/lib/ArduinoJson/library.properties deleted file mode 100644 index f9dd1dd1..00000000 --- a/lib/ArduinoJson/library.properties +++ /dev/null @@ -1,11 +0,0 @@ -name=ArduinoJson -version=5.13.3 -author=Benoit Blanchon -maintainer=Benoit Blanchon -sentence=An efficient and elegant JSON library for Arduino. -paragraph=ArduinoJson supports ✔ serialization, ✔ deserialization, ✔ fixed allocation, ✔ zero-copy, ✔ streams, and more. It is the most popular Arduino library on GitHub â¤â¤â¤â¤â¤. Check out arduinojson.org for a comprehensive documentation. -category=Data Processing -url=https://arduinojson.org/?utm_source=meta&utm_medium=library.properties -architectures=* -repository=https://github.com/bblanchon/ArduinoJson.git -license=MIT diff --git a/lib/ArduinoJson/src/ArduinoJson.h b/lib/ArduinoJson/src/ArduinoJson.h deleted file mode 100644 index 3782aeab..00000000 --- a/lib/ArduinoJson/src/ArduinoJson.h +++ /dev/null @@ -1,17 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#ifdef __cplusplus - -#include "ArduinoJson.hpp" - -using namespace ArduinoJson; - -#else - -#error ArduinoJson requires a C++ compiler, please change file extension to .cc or .cpp - -#endif diff --git a/lib/ArduinoJson/src/ArduinoJson.hpp b/lib/ArduinoJson/src/ArduinoJson.hpp deleted file mode 100644 index c493c06a..00000000 --- a/lib/ArduinoJson/src/ArduinoJson.hpp +++ /dev/null @@ -1,19 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#include "ArduinoJson/version.hpp" - -#include "ArduinoJson/DynamicJsonBuffer.hpp" -#include "ArduinoJson/JsonArray.hpp" -#include "ArduinoJson/JsonObject.hpp" -#include "ArduinoJson/StaticJsonBuffer.hpp" - -#include "ArduinoJson/Deserialization/JsonParserImpl.hpp" -#include "ArduinoJson/JsonArrayImpl.hpp" -#include "ArduinoJson/JsonBufferImpl.hpp" -#include "ArduinoJson/JsonObjectImpl.hpp" -#include "ArduinoJson/JsonVariantImpl.hpp" -#include "ArduinoJson/Serialization/JsonSerializerImpl.hpp" diff --git a/lib/ArduinoJson/src/ArduinoJson/Configuration.hpp b/lib/ArduinoJson/src/ArduinoJson/Configuration.hpp deleted file mode 100644 index 82483adf..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/Configuration.hpp +++ /dev/null @@ -1,151 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -// Small or big machine? -#ifndef ARDUINOJSON_EMBEDDED_MODE -#if defined(ARDUINO) || defined(__IAR_SYSTEMS_ICC__) || defined(__XC) || \ - defined(__ARMCC_VERSION) -#define ARDUINOJSON_EMBEDDED_MODE 1 -#else -#define ARDUINOJSON_EMBEDDED_MODE 0 -#endif -#endif - -#if ARDUINOJSON_EMBEDDED_MODE - -// Store floats by default to reduce the memory usage (issue #134) -#ifndef ARDUINOJSON_USE_DOUBLE -#define ARDUINOJSON_USE_DOUBLE 0 -#endif - -// Store longs by default, because they usually match the size of a float. -#ifndef ARDUINOJSON_USE_LONG_LONG -#define ARDUINOJSON_USE_LONG_LONG 0 -#endif -#ifndef ARDUINOJSON_USE_INT64 -#define ARDUINOJSON_USE_INT64 0 -#endif - -// Embedded systems usually don't have std::string -#ifndef ARDUINOJSON_ENABLE_STD_STRING -#define ARDUINOJSON_ENABLE_STD_STRING 0 -#endif - -// Embedded systems usually don't have std::stream -#ifndef ARDUINOJSON_ENABLE_STD_STREAM -#define ARDUINOJSON_ENABLE_STD_STREAM 0 -#endif - -// Limit nesting as the stack is likely to be small -#ifndef ARDUINOJSON_DEFAULT_NESTING_LIMIT -#define ARDUINOJSON_DEFAULT_NESTING_LIMIT 10 -#endif - -#else // ARDUINOJSON_EMBEDDED_MODE - -// On a computer we have plenty of memory so we can use doubles -#ifndef ARDUINOJSON_USE_DOUBLE -#define ARDUINOJSON_USE_DOUBLE 1 -#endif - -// Use long long when available -#ifndef ARDUINOJSON_USE_LONG_LONG -#if __cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1800) -#define ARDUINOJSON_USE_LONG_LONG 1 -#else -#define ARDUINOJSON_USE_LONG_LONG 0 -#endif -#endif - -// Use _int64 on old versions of Visual Studio -#ifndef ARDUINOJSON_USE_INT64 -#if defined(_MSC_VER) && _MSC_VER <= 1700 -#define ARDUINOJSON_USE_INT64 1 -#else -#define ARDUINOJSON_USE_INT64 0 -#endif -#endif - -// On a computer, we can use std::string -#ifndef ARDUINOJSON_ENABLE_STD_STRING -#define ARDUINOJSON_ENABLE_STD_STRING 1 -#endif - -// On a computer, we can assume std::stream -#ifndef ARDUINOJSON_ENABLE_STD_STREAM -#define ARDUINOJSON_ENABLE_STD_STREAM 1 -#endif - -// On a computer, the stack is large so we can increase nesting limit -#ifndef ARDUINOJSON_DEFAULT_NESTING_LIMIT -#define ARDUINOJSON_DEFAULT_NESTING_LIMIT 50 -#endif - -#endif // ARDUINOJSON_EMBEDDED_MODE - -#ifdef ARDUINO - -// Enable support for Arduino String -#ifndef ARDUINOJSON_ENABLE_ARDUINO_STRING -#define ARDUINOJSON_ENABLE_ARDUINO_STRING 1 -#endif - -// Enable support for Arduino Stream -#ifndef ARDUINOJSON_ENABLE_ARDUINO_STREAM -#define ARDUINOJSON_ENABLE_ARDUINO_STREAM 1 -#endif - -#else // ARDUINO - -// Disable support for Arduino String -#ifndef ARDUINOJSON_ENABLE_ARDUINO_STRING -#define ARDUINOJSON_ENABLE_ARDUINO_STRING 0 -#endif - -// Disable support for Arduino Stream -#ifndef ARDUINOJSON_ENABLE_ARDUINO_STREAM -#define ARDUINOJSON_ENABLE_ARDUINO_STREAM 0 -#endif - -#endif // ARDUINO - -#ifndef ARDUINOJSON_ENABLE_PROGMEM -#ifdef PROGMEM -#define ARDUINOJSON_ENABLE_PROGMEM 1 -#else -#define ARDUINOJSON_ENABLE_PROGMEM 0 -#endif -#endif - -#ifndef ARDUINOJSON_ENABLE_ALIGNMENT -#ifdef ARDUINO_ARCH_AVR -// alignment isn't needed for 8-bit AVR -#define ARDUINOJSON_ENABLE_ALIGNMENT 0 -#else -// but most processors need pointers to be align on word size -#define ARDUINOJSON_ENABLE_ALIGNMENT 1 -#endif -#endif - -// Enable deprecated functions by default -#ifndef ARDUINOJSON_ENABLE_DEPRECATED -#define ARDUINOJSON_ENABLE_DEPRECATED 1 -#endif - -// Control the exponentiation threshold for big numbers -// CAUTION: cannot be more that 1e9 !!!! -#ifndef ARDUINOJSON_POSITIVE_EXPONENTIATION_THRESHOLD -#define ARDUINOJSON_POSITIVE_EXPONENTIATION_THRESHOLD 1e7 -#endif - -// Control the exponentiation threshold for small numbers -#ifndef ARDUINOJSON_NEGATIVE_EXPONENTIATION_THRESHOLD -#define ARDUINOJSON_NEGATIVE_EXPONENTIATION_THRESHOLD 1e-5 -#endif - -#if ARDUINOJSON_USE_LONG_LONG && ARDUINOJSON_USE_INT64 -#error ARDUINOJSON_USE_LONG_LONG and ARDUINOJSON_USE_INT64 cannot be set together -#endif diff --git a/lib/ArduinoJson/src/ArduinoJson/Data/Encoding.hpp b/lib/ArduinoJson/src/ArduinoJson/Data/Encoding.hpp deleted file mode 100644 index a0efa2c7..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/Data/Encoding.hpp +++ /dev/null @@ -1,37 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -namespace ArduinoJson { -namespace Internals { - -class Encoding { - public: - // Optimized for code size on a 8-bit AVR - static char escapeChar(char c) { - const char *p = escapeTable(false); - while (p[0] && p[1] != c) { - p += 2; - } - return p[0]; - } - - // Optimized for code size on a 8-bit AVR - static char unescapeChar(char c) { - const char *p = escapeTable(true); - for (;;) { - if (p[0] == '\0') return c; - if (p[0] == c) return p[1]; - p += 2; - } - } - - private: - static const char *escapeTable(bool excludeIdenticals) { - return &"\"\"\\\\b\bf\fn\nr\rt\t"[excludeIdenticals ? 4 : 0]; - } -}; -} -} diff --git a/lib/ArduinoJson/src/ArduinoJson/Data/JsonBufferAllocated.hpp b/lib/ArduinoJson/src/ArduinoJson/Data/JsonBufferAllocated.hpp deleted file mode 100644 index 443aae4d..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/Data/JsonBufferAllocated.hpp +++ /dev/null @@ -1,22 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#include "../JsonBuffer.hpp" - -namespace ArduinoJson { -namespace Internals { - -class JsonBufferAllocated { - public: - void *operator new(size_t n, JsonBuffer *jsonBuffer) throw() { - if (!jsonBuffer) return NULL; - return jsonBuffer->alloc(n); - } - - void operator delete(void *, JsonBuffer *)throw(); -}; -} -} diff --git a/lib/ArduinoJson/src/ArduinoJson/Data/JsonFloat.hpp b/lib/ArduinoJson/src/ArduinoJson/Data/JsonFloat.hpp deleted file mode 100644 index 0ed42140..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/Data/JsonFloat.hpp +++ /dev/null @@ -1,18 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#include "../Configuration.hpp" - -namespace ArduinoJson { -namespace Internals { - -#if ARDUINOJSON_USE_DOUBLE -typedef double JsonFloat; -#else -typedef float JsonFloat; -#endif -} -} diff --git a/lib/ArduinoJson/src/ArduinoJson/Data/JsonInteger.hpp b/lib/ArduinoJson/src/ArduinoJson/Data/JsonInteger.hpp deleted file mode 100644 index c8ddd00b..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/Data/JsonInteger.hpp +++ /dev/null @@ -1,23 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#include "../Configuration.hpp" - -namespace ArduinoJson { -namespace Internals { - -#if ARDUINOJSON_USE_LONG_LONG -typedef long long JsonInteger; -typedef unsigned long long JsonUInt; -#elif ARDUINOJSON_USE_INT64 -typedef __int64 JsonInteger; -typedef unsigned _int64 JsonUInt; -#else -typedef long JsonInteger; -typedef unsigned long JsonUInt; -#endif -} -} diff --git a/lib/ArduinoJson/src/ArduinoJson/Data/JsonVariantAs.hpp b/lib/ArduinoJson/src/ArduinoJson/Data/JsonVariantAs.hpp deleted file mode 100644 index 8f202c5e..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/Data/JsonVariantAs.hpp +++ /dev/null @@ -1,42 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -namespace ArduinoJson { -namespace Internals { - -// A metafunction that returns the type of the value returned by -// JsonVariant::as() -template -struct JsonVariantAs { - typedef T type; -}; - -template <> -struct JsonVariantAs { - typedef const char* type; -}; - -template <> -struct JsonVariantAs { - typedef JsonArray& type; -}; - -template <> -struct JsonVariantAs { - typedef const JsonArray& type; -}; - -template <> -struct JsonVariantAs { - typedef JsonObject& type; -}; - -template <> -struct JsonVariantAs { - typedef const JsonObject& type; -}; -} -} diff --git a/lib/ArduinoJson/src/ArduinoJson/Data/JsonVariantContent.hpp b/lib/ArduinoJson/src/ArduinoJson/Data/JsonVariantContent.hpp deleted file mode 100644 index c525a606..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/Data/JsonVariantContent.hpp +++ /dev/null @@ -1,27 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#include "JsonFloat.hpp" -#include "JsonInteger.hpp" - -namespace ArduinoJson { - -// Forward declarations -class JsonArray; -class JsonObject; - -namespace Internals { -// A union that defines the actual content of a JsonVariant. -// The enum JsonVariantType determines which member is in use. -union JsonVariantContent { - JsonFloat asFloat; // used for double and float - JsonUInt asInteger; // used for bool, char, short, int and longs - const char* asString; // asString can be null - JsonArray* asArray; // asArray cannot be null - JsonObject* asObject; // asObject cannot be null -}; -} -} diff --git a/lib/ArduinoJson/src/ArduinoJson/Data/JsonVariantDefault.hpp b/lib/ArduinoJson/src/ArduinoJson/Data/JsonVariantDefault.hpp deleted file mode 100644 index 57ecc83e..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/Data/JsonVariantDefault.hpp +++ /dev/null @@ -1,23 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -namespace ArduinoJson { -namespace Internals { - -template -struct JsonVariantDefault { - static T get() { - return T(); - } -}; - -template -struct JsonVariantDefault : JsonVariantDefault {}; - -template -struct JsonVariantDefault : JsonVariantDefault {}; -} -} diff --git a/lib/ArduinoJson/src/ArduinoJson/Data/JsonVariantType.hpp b/lib/ArduinoJson/src/ArduinoJson/Data/JsonVariantType.hpp deleted file mode 100644 index 21f890e5..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/Data/JsonVariantType.hpp +++ /dev/null @@ -1,27 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -namespace ArduinoJson { -class JsonArray; -class JsonObject; - -namespace Internals { - -// Enumerated type to know the current type of a JsonVariant. -// The value determines which member of JsonVariantContent is used. -enum JsonVariantType { - JSON_UNDEFINED, // JsonVariant has not been initialized - JSON_UNPARSED, // JsonVariant contains an unparsed string - JSON_STRING, // JsonVariant stores a const char* - JSON_BOOLEAN, // JsonVariant stores a bool - JSON_POSITIVE_INTEGER, // JsonVariant stores an JsonUInt - JSON_NEGATIVE_INTEGER, // JsonVariant stores an JsonUInt that must be negated - JSON_ARRAY, // JsonVariant stores a pointer to a JsonArray - JSON_OBJECT, // JsonVariant stores a pointer to a JsonObject - JSON_FLOAT // JsonVariant stores a JsonFloat -}; -} -} diff --git a/lib/ArduinoJson/src/ArduinoJson/Data/List.hpp b/lib/ArduinoJson/src/ArduinoJson/Data/List.hpp deleted file mode 100644 index 506308cc..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/Data/List.hpp +++ /dev/null @@ -1,94 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#include "../JsonBuffer.hpp" -#include "ListConstIterator.hpp" -#include "ListIterator.hpp" - -namespace ArduinoJson { -namespace Internals { - -// A singly linked list of T. -// The linked list is composed of ListNode. -// It is derived by JsonArray and JsonObject -template -class List { - public: - typedef T value_type; - typedef ListNode node_type; - typedef ListIterator iterator; - typedef ListConstIterator const_iterator; - - // Creates an empty List attached to a JsonBuffer. - // The JsonBuffer allows to allocate new nodes. - // When buffer is NULL, the List is not able to grow and success() returns - // false. This is used to identify bad memory allocations and parsing - // failures. - explicit List(JsonBuffer *buffer) : _buffer(buffer), _firstNode(NULL) {} - - // Returns true if the object is valid - // Would return false in the following situation: - // - the memory allocation failed (StaticJsonBuffer was too small) - // - the JSON parsing failed - bool success() const { - return _buffer != NULL; - } - - // Returns the numbers of elements in the list. - // For a JsonObject, it would return the number of key-value pairs - size_t size() const { - size_t nodeCount = 0; - for (node_type *node = _firstNode; node; node = node->next) nodeCount++; - return nodeCount; - } - - iterator add() { - node_type *newNode = new (_buffer) node_type(); - - if (_firstNode) { - node_type *lastNode = _firstNode; - while (lastNode->next) lastNode = lastNode->next; - lastNode->next = newNode; - } else { - _firstNode = newNode; - } - - return iterator(newNode); - } - - iterator begin() { - return iterator(_firstNode); - } - iterator end() { - return iterator(NULL); - } - - const_iterator begin() const { - return const_iterator(_firstNode); - } - const_iterator end() const { - return const_iterator(NULL); - } - - void remove(iterator it) { - node_type *nodeToRemove = it._node; - if (!nodeToRemove) return; - if (nodeToRemove == _firstNode) { - _firstNode = nodeToRemove->next; - } else { - for (node_type *node = _firstNode; node; node = node->next) - if (node->next == nodeToRemove) node->next = nodeToRemove->next; - } - } - - protected: - JsonBuffer *_buffer; - - private: - node_type *_firstNode; -}; -} -} diff --git a/lib/ArduinoJson/src/ArduinoJson/Data/ListConstIterator.hpp b/lib/ArduinoJson/src/ArduinoJson/Data/ListConstIterator.hpp deleted file mode 100644 index a6af685e..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/Data/ListConstIterator.hpp +++ /dev/null @@ -1,50 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#include "ListNode.hpp" - -namespace ArduinoJson { -namespace Internals { - -// A read-only forward itertor for List -template -class ListConstIterator { - public: - explicit ListConstIterator(const ListNode *node = NULL) : _node(node) {} - - const T &operator*() const { - return _node->content; - } - const T *operator->() { - return &_node->content; - } - - bool operator==(const ListConstIterator &other) const { - return _node == other._node; - } - - bool operator!=(const ListConstIterator &other) const { - return _node != other._node; - } - - ListConstIterator &operator++() { - if (_node) _node = _node->next; - return *this; - } - - ListConstIterator &operator+=(size_t distance) { - while (_node && distance) { - _node = _node->next; - --distance; - } - return *this; - } - - private: - const ListNode *_node; -}; -} -} diff --git a/lib/ArduinoJson/src/ArduinoJson/Data/ListIterator.hpp b/lib/ArduinoJson/src/ArduinoJson/Data/ListIterator.hpp deleted file mode 100644 index 01fa287f..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/Data/ListIterator.hpp +++ /dev/null @@ -1,60 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#include "ListConstIterator.hpp" -#include "ListNode.hpp" - -namespace ArduinoJson { -namespace Internals { - -template -class List; - -// A read-write forward iterator for List -template -class ListIterator { - friend class List; - - public: - explicit ListIterator(ListNode *node = NULL) : _node(node) {} - - T &operator*() const { - return _node->content; - } - T *operator->() { - return &_node->content; - } - - bool operator==(const ListIterator &other) const { - return _node == other._node; - } - - bool operator!=(const ListIterator &other) const { - return _node != other._node; - } - - ListIterator &operator++() { - if (_node) _node = _node->next; - return *this; - } - - ListIterator &operator+=(size_t distance) { - while (_node && distance) { - _node = _node->next; - --distance; - } - return *this; - } - - operator ListConstIterator() const { - return ListConstIterator(_node); - } - - private: - ListNode *_node; -}; -} -} diff --git a/lib/ArduinoJson/src/ArduinoJson/Data/ListNode.hpp b/lib/ArduinoJson/src/ArduinoJson/Data/ListNode.hpp deleted file mode 100644 index c0907120..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/Data/ListNode.hpp +++ /dev/null @@ -1,24 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#include // for NULL - -#include "JsonBufferAllocated.hpp" - -namespace ArduinoJson { -namespace Internals { - -// A node for a singly-linked list. -// Used by List and its iterators. -template -struct ListNode : public Internals::JsonBufferAllocated { - ListNode() throw() : next(NULL) {} - - ListNode *next; - T content; -}; -} -} diff --git a/lib/ArduinoJson/src/ArduinoJson/Data/NonCopyable.hpp b/lib/ArduinoJson/src/ArduinoJson/Data/NonCopyable.hpp deleted file mode 100644 index 73f3d8ed..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/Data/NonCopyable.hpp +++ /dev/null @@ -1,23 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -namespace ArduinoJson { -namespace Internals { - -// A type that cannot be copied -class NonCopyable { - protected: - NonCopyable() {} - - private: - // copy constructor is private - NonCopyable(const NonCopyable&); - - // copy operator is private - NonCopyable& operator=(const NonCopyable&); -}; -} -} diff --git a/lib/ArduinoJson/src/ArduinoJson/Data/ReferenceType.hpp b/lib/ArduinoJson/src/ArduinoJson/Data/ReferenceType.hpp deleted file mode 100644 index 1e491172..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/Data/ReferenceType.hpp +++ /dev/null @@ -1,24 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -namespace ArduinoJson { -namespace Internals { - -// A type that is meant to be used by reference only (JsonArray and JsonObject) -class ReferenceType { - public: - bool operator==(const ReferenceType& other) const { - // two JsonArray are equal if they are the same instance - // (we don't compare the content) - return this == &other; - } - - bool operator!=(const ReferenceType& other) const { - return this != &other; - } -}; -} -} diff --git a/lib/ArduinoJson/src/ArduinoJson/Data/ValueSaver.hpp b/lib/ArduinoJson/src/ArduinoJson/Data/ValueSaver.hpp deleted file mode 100644 index 9750f1ac..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/Data/ValueSaver.hpp +++ /dev/null @@ -1,52 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#include "../JsonBuffer.hpp" -#include "../JsonVariant.hpp" -#include "../StringTraits/StringTraits.hpp" -#include "../TypeTraits/EnableIf.hpp" - -namespace ArduinoJson { -namespace Internals { - -template -struct ValueSaver { - template - static bool save(JsonBuffer*, Destination& destination, Source source) { - destination = source; - return true; - } -}; - -template -struct ValueSaver< - Source, typename EnableIf::should_duplicate>::type> { - template - static bool save(JsonBuffer* buffer, Destination& dest, Source source) { - if (!StringTraits::is_null(source)) { - typename StringTraits::duplicate_t dup = - StringTraits::duplicate(source, buffer); - if (!dup) return false; - dest = dup; - } else { - dest = reinterpret_cast(0); - } - return true; - } -}; - -// const char*, const signed char*, const unsigned char* -template -struct ValueSaver< - Char*, typename EnableIf::should_duplicate>::type> { - template - static bool save(JsonBuffer*, Destination& dest, Char* source) { - dest = reinterpret_cast(source); - return true; - } -}; -} -} diff --git a/lib/ArduinoJson/src/ArduinoJson/Deserialization/Comments.hpp b/lib/ArduinoJson/src/ArduinoJson/Deserialization/Comments.hpp deleted file mode 100644 index c2c48ebc..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/Deserialization/Comments.hpp +++ /dev/null @@ -1,61 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -namespace ArduinoJson { -namespace Internals { -template -void skipSpacesAndComments(TInput& input) { - for (;;) { - switch (input.current()) { - // spaces - case ' ': - case '\t': - case '\r': - case '\n': - input.move(); - continue; - - // comments - case '/': - switch (input.next()) { - // C-style block comment - case '*': - input.move(); // skip '/' - // no need to skip '*' - for (;;) { - input.move(); - if (input.current() == '\0') return; - if (input.current() == '*' && input.next() == '/') { - input.move(); // skip '*' - input.move(); // skip '/' - break; - } - } - break; - - // C++-style line comment - case '/': - // not need to skip "//" - for (;;) { - input.move(); - if (input.current() == '\0') return; - if (input.current() == '\n') break; - } - break; - - // not a comment, just a '/' - default: - return; - } - break; - - default: - return; - } - } -} -} -} diff --git a/lib/ArduinoJson/src/ArduinoJson/Deserialization/JsonParser.hpp b/lib/ArduinoJson/src/ArduinoJson/Deserialization/JsonParser.hpp deleted file mode 100644 index 4cbaf454..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/Deserialization/JsonParser.hpp +++ /dev/null @@ -1,102 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#include "../JsonBuffer.hpp" -#include "../JsonVariant.hpp" -#include "../TypeTraits/IsConst.hpp" -#include "StringWriter.hpp" - -namespace ArduinoJson { -namespace Internals { - -// Parse JSON string to create JsonArrays and JsonObjects -// This internal class is not indended to be used directly. -// Instead, use JsonBuffer.parseArray() or .parseObject() -template -class JsonParser { - public: - JsonParser(JsonBuffer *buffer, TReader reader, TWriter writer, - uint8_t nestingLimit) - : _buffer(buffer), - _reader(reader), - _writer(writer), - _nestingLimit(nestingLimit) {} - - JsonArray &parseArray(); - JsonObject &parseObject(); - - JsonVariant parseVariant() { - JsonVariant result; - parseAnythingTo(&result); - return result; - } - - private: - JsonParser &operator=(const JsonParser &); // non-copiable - - static bool eat(TReader &, char charToSkip); - FORCE_INLINE bool eat(char charToSkip) { - return eat(_reader, charToSkip); - } - - const char *parseString(); - bool parseAnythingTo(JsonVariant *destination); - - inline bool parseArrayTo(JsonVariant *destination); - inline bool parseObjectTo(JsonVariant *destination); - inline bool parseStringTo(JsonVariant *destination); - - static inline bool isBetween(char c, char min, char max) { - return min <= c && c <= max; - } - - static inline bool canBeInNonQuotedString(char c) { - return isBetween(c, '0', '9') || isBetween(c, '_', 'z') || - isBetween(c, 'A', 'Z') || c == '+' || c == '-' || c == '.'; - } - - static inline bool isQuote(char c) { - return c == '\'' || c == '\"'; - } - - JsonBuffer *_buffer; - TReader _reader; - TWriter _writer; - uint8_t _nestingLimit; -}; - -template -struct JsonParserBuilder { - typedef typename StringTraits::Reader InputReader; - typedef JsonParser TParser; - - static TParser makeParser(TJsonBuffer *buffer, TString &json, - uint8_t nestingLimit) { - return TParser(buffer, InputReader(json), *buffer, nestingLimit); - } -}; - -template -struct JsonParserBuilder::value>::type> { - typedef typename StringTraits::Reader TReader; - typedef StringWriter TWriter; - typedef JsonParser TParser; - - static TParser makeParser(TJsonBuffer *buffer, TChar *json, - uint8_t nestingLimit) { - return TParser(buffer, TReader(json), TWriter(json), nestingLimit); - } -}; - -template -inline typename JsonParserBuilder::TParser makeParser( - TJsonBuffer *buffer, TString &json, uint8_t nestingLimit) { - return JsonParserBuilder::makeParser(buffer, json, - nestingLimit); -} -} // namespace Internals -} // namespace ArduinoJson diff --git a/lib/ArduinoJson/src/ArduinoJson/Deserialization/JsonParserImpl.hpp b/lib/ArduinoJson/src/ArduinoJson/Deserialization/JsonParserImpl.hpp deleted file mode 100644 index 50426735..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/Deserialization/JsonParserImpl.hpp +++ /dev/null @@ -1,189 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#include "Comments.hpp" -#include "JsonParser.hpp" - -template -inline bool ArduinoJson::Internals::JsonParser::eat( - TReader &reader, char charToSkip) { - skipSpacesAndComments(reader); - if (reader.current() != charToSkip) return false; - reader.move(); - return true; -} - -template -inline bool -ArduinoJson::Internals::JsonParser::parseAnythingTo( - JsonVariant *destination) { - skipSpacesAndComments(_reader); - - switch (_reader.current()) { - case '[': - return parseArrayTo(destination); - - case '{': - return parseObjectTo(destination); - - default: - return parseStringTo(destination); - } -} - -template -inline ArduinoJson::JsonArray & -ArduinoJson::Internals::JsonParser::parseArray() { - if (_nestingLimit == 0) return JsonArray::invalid(); - _nestingLimit--; - - // Create an empty array - JsonArray &array = _buffer->createArray(); - - // Check opening braket - if (!eat('[')) goto ERROR_MISSING_BRACKET; - if (eat(']')) goto SUCCESS_EMPTY_ARRAY; - - // Read each value - for (;;) { - // 1 - Parse value - JsonVariant value; - if (!parseAnythingTo(&value)) goto ERROR_INVALID_VALUE; - if (!array.add(value)) goto ERROR_NO_MEMORY; - - // 2 - More values? - if (eat(']')) goto SUCCES_NON_EMPTY_ARRAY; - if (!eat(',')) goto ERROR_MISSING_COMMA; - } - -SUCCESS_EMPTY_ARRAY: -SUCCES_NON_EMPTY_ARRAY: - _nestingLimit++; - return array; - -ERROR_INVALID_VALUE: -ERROR_MISSING_BRACKET: -ERROR_MISSING_COMMA: -ERROR_NO_MEMORY: - return JsonArray::invalid(); -} - -template -inline bool ArduinoJson::Internals::JsonParser::parseArrayTo( - JsonVariant *destination) { - JsonArray &array = parseArray(); - if (!array.success()) return false; - - *destination = array; - return true; -} - -template -inline ArduinoJson::JsonObject & -ArduinoJson::Internals::JsonParser::parseObject() { - if (_nestingLimit == 0) return JsonObject::invalid(); - _nestingLimit--; - - // Create an empty object - JsonObject &object = _buffer->createObject(); - - // Check opening brace - if (!eat('{')) goto ERROR_MISSING_BRACE; - if (eat('}')) goto SUCCESS_EMPTY_OBJECT; - - // Read each key value pair - for (;;) { - // 1 - Parse key - const char *key = parseString(); - if (!key) goto ERROR_INVALID_KEY; - if (!eat(':')) goto ERROR_MISSING_COLON; - - // 2 - Parse value - JsonVariant value; - if (!parseAnythingTo(&value)) goto ERROR_INVALID_VALUE; - if (!object.set(key, value)) goto ERROR_NO_MEMORY; - - // 3 - More keys/values? - if (eat('}')) goto SUCCESS_NON_EMPTY_OBJECT; - if (!eat(',')) goto ERROR_MISSING_COMMA; - } - -SUCCESS_EMPTY_OBJECT: -SUCCESS_NON_EMPTY_OBJECT: - _nestingLimit++; - return object; - -ERROR_INVALID_KEY: -ERROR_INVALID_VALUE: -ERROR_MISSING_BRACE: -ERROR_MISSING_COLON: -ERROR_MISSING_COMMA: -ERROR_NO_MEMORY: - return JsonObject::invalid(); -} - -template -inline bool ArduinoJson::Internals::JsonParser::parseObjectTo( - JsonVariant *destination) { - JsonObject &object = parseObject(); - if (!object.success()) return false; - - *destination = object; - return true; -} - -template -inline const char * -ArduinoJson::Internals::JsonParser::parseString() { - typename RemoveReference::type::String str = _writer.startString(); - - skipSpacesAndComments(_reader); - char c = _reader.current(); - - if (isQuote(c)) { // quotes - _reader.move(); - char stopChar = c; - for (;;) { - c = _reader.current(); - if (c == '\0') break; - _reader.move(); - - if (c == stopChar) break; - - if (c == '\\') { - // replace char - c = Encoding::unescapeChar(_reader.current()); - if (c == '\0') break; - _reader.move(); - } - - str.append(c); - } - } else { // no quotes - for (;;) { - if (!canBeInNonQuotedString(c)) break; - _reader.move(); - str.append(c); - c = _reader.current(); - } - } - - return str.c_str(); -} - -template -inline bool ArduinoJson::Internals::JsonParser::parseStringTo( - JsonVariant *destination) { - bool hasQuotes = isQuote(_reader.current()); - const char *value = parseString(); - if (value == NULL) return false; - if (hasQuotes) { - *destination = value; - } else { - *destination = RawJson(value); - } - return true; -} diff --git a/lib/ArduinoJson/src/ArduinoJson/Deserialization/StringWriter.hpp b/lib/ArduinoJson/src/ArduinoJson/Deserialization/StringWriter.hpp deleted file mode 100644 index fd5507ea..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/Deserialization/StringWriter.hpp +++ /dev/null @@ -1,41 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -namespace ArduinoJson { -namespace Internals { - -template -class StringWriter { - public: - class String { - public: - String(TChar** ptr) : _writePtr(ptr), _startPtr(*ptr) {} - - void append(char c) { - *(*_writePtr)++ = TChar(c); - } - - const char* c_str() const { - *(*_writePtr)++ = 0; - return reinterpret_cast(_startPtr); - } - - private: - TChar** _writePtr; - TChar* _startPtr; - }; - - StringWriter(TChar* buffer) : _ptr(buffer) {} - - String startString() { - return String(&_ptr); - } - - private: - TChar* _ptr; -}; -} -} diff --git a/lib/ArduinoJson/src/ArduinoJson/DynamicJsonBuffer.hpp b/lib/ArduinoJson/src/ArduinoJson/DynamicJsonBuffer.hpp deleted file mode 100644 index bdbd5dd9..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/DynamicJsonBuffer.hpp +++ /dev/null @@ -1,170 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#include "JsonBufferBase.hpp" - -#include - -#if defined(__clang__) -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wnon-virtual-dtor" -#elif defined(__GNUC__) -#if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6) -#pragma GCC diagnostic push -#endif -#pragma GCC diagnostic ignored "-Wnon-virtual-dtor" -#endif - -namespace ArduinoJson { -namespace Internals { -class DefaultAllocator { - public: - void* allocate(size_t size) { - return malloc(size); - } - void deallocate(void* pointer) { - free(pointer); - } -}; - -template -class DynamicJsonBufferBase - : public JsonBufferBase > { - struct Block; - struct EmptyBlock { - Block* next; - size_t capacity; - size_t size; - }; - struct Block : EmptyBlock { - uint8_t data[1]; - }; - - public: - enum { EmptyBlockSize = sizeof(EmptyBlock) }; - - DynamicJsonBufferBase(size_t initialSize = 256) - : _head(NULL), _nextBlockCapacity(initialSize) {} - - ~DynamicJsonBufferBase() { - clear(); - } - - // Gets the number of bytes occupied in the buffer - size_t size() const { - size_t total = 0; - for (const Block* b = _head; b; b = b->next) total += b->size; - return total; - } - - // Allocates the specified amount of bytes in the buffer - virtual void* alloc(size_t bytes) { - alignNextAlloc(); - return canAllocInHead(bytes) ? allocInHead(bytes) : allocInNewBlock(bytes); - } - - // Resets the buffer. - // USE WITH CAUTION: this invalidates all previously allocated data - void clear() { - Block* currentBlock = _head; - while (currentBlock != NULL) { - _nextBlockCapacity = currentBlock->capacity; - Block* nextBlock = currentBlock->next; - _allocator.deallocate(currentBlock); - currentBlock = nextBlock; - } - _head = 0; - } - - class String { - public: - String(DynamicJsonBufferBase* parent) - : _parent(parent), _start(NULL), _length(0) {} - - void append(char c) { - if (_parent->canAllocInHead(1)) { - char* end = static_cast(_parent->allocInHead(1)); - *end = c; - if (_length == 0) _start = end; - } else { - char* newStart = - static_cast(_parent->allocInNewBlock(_length + 1)); - if (_start && newStart) memcpy(newStart, _start, _length); - if (newStart) newStart[_length] = c; - _start = newStart; - } - _length++; - } - - const char* c_str() { - append(0); - return _start; - } - - private: - DynamicJsonBufferBase* _parent; - char* _start; - size_t _length; - }; - - String startString() { - return String(this); - } - - private: - void alignNextAlloc() { - if (_head) _head->size = this->round_size_up(_head->size); - } - - bool canAllocInHead(size_t bytes) const { - return _head != NULL && _head->size + bytes <= _head->capacity; - } - - void* allocInHead(size_t bytes) { - void* p = _head->data + _head->size; - _head->size += bytes; - return p; - } - - void* allocInNewBlock(size_t bytes) { - size_t capacity = _nextBlockCapacity; - if (bytes > capacity) capacity = bytes; - if (!addNewBlock(capacity)) return NULL; - _nextBlockCapacity *= 2; - return allocInHead(bytes); - } - - bool addNewBlock(size_t capacity) { - size_t bytes = EmptyBlockSize + capacity; - Block* block = static_cast(_allocator.allocate(bytes)); - if (block == NULL) return false; - block->capacity = capacity; - block->size = 0; - block->next = _head; - _head = block; - return true; - } - - TAllocator _allocator; - Block* _head; - size_t _nextBlockCapacity; -}; -} - -#if defined(__clang__) -#pragma clang diagnostic pop -#elif defined(__GNUC__) -#if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6) -#pragma GCC diagnostic pop -#endif -#endif - -// Implements a JsonBuffer with dynamic memory allocation. -// You are strongly encouraged to consider using StaticJsonBuffer which is much -// more suitable for embedded systems. -typedef Internals::DynamicJsonBufferBase - DynamicJsonBuffer; -} diff --git a/lib/ArduinoJson/src/ArduinoJson/JsonArray.hpp b/lib/ArduinoJson/src/ArduinoJson/JsonArray.hpp deleted file mode 100644 index 2acd2a1a..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/JsonArray.hpp +++ /dev/null @@ -1,227 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#include "Data/JsonBufferAllocated.hpp" -#include "Data/List.hpp" -#include "Data/ReferenceType.hpp" -#include "Data/ValueSaver.hpp" -#include "JsonVariant.hpp" -#include "Serialization/JsonPrintable.hpp" -#include "StringTraits/StringTraits.hpp" -#include "TypeTraits/EnableIf.hpp" -#include "TypeTraits/IsArray.hpp" -#include "TypeTraits/IsFloatingPoint.hpp" -#include "TypeTraits/IsSame.hpp" - -// Returns the size (in bytes) of an array with n elements. -// Can be very handy to determine the size of a StaticJsonBuffer. -#define JSON_ARRAY_SIZE(NUMBER_OF_ELEMENTS) \ - (sizeof(JsonArray) + (NUMBER_OF_ELEMENTS) * sizeof(JsonArray::node_type)) - -namespace ArduinoJson { - -// Forward declarations -class JsonObject; -class JsonBuffer; -namespace Internals { -class JsonArraySubscript; -} - -// An array of JsonVariant. -// -// The constructor is private, instances must be created via -// JsonBuffer::createArray() or JsonBuffer::parseArray(). -// A JsonArray can be serialized to a JSON string via JsonArray::printTo(). -// It can also be deserialized from a JSON string via JsonBuffer::parseArray(). -class JsonArray : public Internals::JsonPrintable, - public Internals::ReferenceType, - public Internals::NonCopyable, - public Internals::List, - public Internals::JsonBufferAllocated { - public: - // Create an empty JsonArray attached to the specified JsonBuffer. - // You should not call this constructor directly. - // Instead, use JsonBuffer::createArray() or JsonBuffer::parseArray(). - explicit JsonArray(JsonBuffer *buffer) throw() - : Internals::List(buffer) {} - - // Gets the value at the specified index - const Internals::JsonArraySubscript operator[](size_t index) const; - - // Gets or sets the value at specified index - Internals::JsonArraySubscript operator[](size_t index); - - // Adds the specified value at the end of the array. - // - // bool add(TValue); - // TValue = bool, long, int, short, float, double, RawJson, JsonVariant, - // std::string, String, JsonArray, JsonObject - template - bool add(const T &value) { - return add_impl(value); - } - // - // bool add(TValue); - // TValue = char*, const char*, const FlashStringHelper* - template - bool add(T *value) { - return add_impl(value); - } - // - // bool add(TValue value, uint8_t decimals); - // TValue = float, double - template - DEPRECATED("Second argument is not supported anymore") - bool add(T value, uint8_t) { - return add_impl(JsonVariant(value)); - } - - // Sets the value at specified index. - // - // bool add(size_t index, const TValue&); - // TValue = bool, long, int, short, float, double, RawJson, JsonVariant, - // std::string, String, JsonArray, JsonObject - template - bool set(size_t index, const T &value) { - return set_impl(index, value); - } - // - // bool add(size_t index, TValue); - // TValue = char*, const char*, const FlashStringHelper* - template - bool set(size_t index, T *value) { - return set_impl(index, value); - } - // - // bool set(size_t index, TValue value, uint8_t decimals); - // TValue = float, double - template - typename Internals::EnableIf::value, bool>::type - set(size_t index, T value, uint8_t decimals) { - return set_impl(index, JsonVariant(value, decimals)); - } - - // Gets the value at the specified index. - template - typename Internals::JsonVariantAs::type get(size_t index) const { - const_iterator it = begin() += index; - return it != end() ? it->as() : Internals::JsonVariantDefault::get(); - } - - // Check the type of the value at specified index. - template - bool is(size_t index) const { - const_iterator it = begin() += index; - return it != end() ? it->is() : false; - } - - // Creates a JsonArray and adds a reference at the end of the array. - // It's a shortcut for JsonBuffer::createArray() and JsonArray::add() - JsonArray &createNestedArray(); - - // Creates a JsonObject and adds a reference at the end of the array. - // It's a shortcut for JsonBuffer::createObject() and JsonArray::add() - JsonObject &createNestedObject(); - - // Removes element at specified index. - void remove(size_t index) { - remove(begin() += index); - } - using Internals::List::remove; - - // Returns a reference an invalid JsonArray. - // This object is meant to replace a NULL pointer. - // This is used when memory allocation or JSON parsing fail. - static JsonArray &invalid() { - static JsonArray instance(NULL); - return instance; - } - - // Imports a 1D array - template - bool copyFrom(T (&array)[N]) { - return copyFrom(array, N); - } - - // Imports a 1D array - template - bool copyFrom(T *array, size_t len) { - bool ok = true; - for (size_t i = 0; i < len; i++) { - ok &= add(array[i]); - } - return ok; - } - - // Imports a 2D array - template - bool copyFrom(T (&array)[N1][N2]) { - bool ok = true; - for (size_t i = 0; i < N1; i++) { - JsonArray &nestedArray = createNestedArray(); - for (size_t j = 0; j < N2; j++) { - ok &= nestedArray.add(array[i][j]); - } - } - return ok; - } - - // Exports a 1D array - template - size_t copyTo(T (&array)[N]) const { - return copyTo(array, N); - } - - // Exports a 1D array - template - size_t copyTo(T *array, size_t len) const { - size_t i = 0; - for (const_iterator it = begin(); it != end() && i < len; ++it) - array[i++] = *it; - return i; - } - - // Exports a 2D array - template - void copyTo(T (&array)[N1][N2]) const { - size_t i = 0; - for (const_iterator it = begin(); it != end() && i < N1; ++it) { - it->as().copyTo(array[i++]); - } - } - -#if ARDUINOJSON_ENABLE_DEPRECATED - DEPRECATED("use remove() instead") - FORCE_INLINE void removeAt(size_t index) { - return remove(index); - } -#endif - - private: - template - bool set_impl(size_t index, TValueRef value) { - iterator it = begin() += index; - if (it == end()) return false; - return Internals::ValueSaver::save(_buffer, *it, value); - } - - template - bool add_impl(TValueRef value) { - iterator it = Internals::List::add(); - if (it == end()) return false; - return Internals::ValueSaver::save(_buffer, *it, value); - } -}; - -namespace Internals { -template <> -struct JsonVariantDefault { - static JsonArray &get() { - return JsonArray::invalid(); - } -}; -} -} diff --git a/lib/ArduinoJson/src/ArduinoJson/JsonArrayImpl.hpp b/lib/ArduinoJson/src/ArduinoJson/JsonArrayImpl.hpp deleted file mode 100644 index 924b7ea7..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/JsonArrayImpl.hpp +++ /dev/null @@ -1,26 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#include "JsonArray.hpp" -#include "JsonArraySubscript.hpp" -#include "JsonObject.hpp" - -namespace ArduinoJson { - -inline JsonArray &JsonArray::createNestedArray() { - if (!_buffer) return JsonArray::invalid(); - JsonArray &array = _buffer->createArray(); - add(array); - return array; -} - -inline JsonObject &JsonArray::createNestedObject() { - if (!_buffer) return JsonObject::invalid(); - JsonObject &object = _buffer->createObject(); - add(object); - return object; -} -} diff --git a/lib/ArduinoJson/src/ArduinoJson/JsonArraySubscript.hpp b/lib/ArduinoJson/src/ArduinoJson/JsonArraySubscript.hpp deleted file mode 100644 index afb4dc1e..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/JsonArraySubscript.hpp +++ /dev/null @@ -1,122 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#include "Configuration.hpp" -#include "JsonVariantBase.hpp" - -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable : 4522) -#endif - -namespace ArduinoJson { -namespace Internals { -class JsonArraySubscript : public JsonVariantBase { - public: - FORCE_INLINE JsonArraySubscript(JsonArray& array, size_t index) - : _array(array), _index(index) {} - - FORCE_INLINE JsonArraySubscript& operator=(const JsonArraySubscript& src) { - _array.set(_index, src); - return *this; - } - - // Replaces the value - // - // operator=(const TValue&) - // TValue = bool, long, int, short, float, double, RawJson, JsonVariant, - // std::string, String, JsonArray, JsonObject - template - FORCE_INLINE JsonArraySubscript& operator=(const T& src) { - _array.set(_index, src); - return *this; - } - // - // operator=(TValue) - // TValue = char*, const char*, const FlashStringHelper* - template - FORCE_INLINE JsonArraySubscript& operator=(T* src) { - _array.set(_index, src); - return *this; - } - - FORCE_INLINE bool success() const { - return _index < _array.size(); - } - - template - FORCE_INLINE typename JsonVariantAs::type as() const { - return _array.get(_index); - } - - template - FORCE_INLINE bool is() const { - return _array.is(_index); - } - - // Replaces the value - // - // bool set(const TValue&) - // TValue = bool, long, int, short, float, double, RawJson, JsonVariant, - // std::string, String, JsonArray, JsonObject - template - FORCE_INLINE bool set(const TValue& value) { - return _array.set(_index, value); - } - // - // bool set(TValue) - // TValue = char*, const char*, const FlashStringHelper* - template - FORCE_INLINE bool set(TValue* value) { - return _array.set(_index, value); - } - // - // bool set(TValue, uint8_t decimals); - // TValue = float, double - template - DEPRECATED("Second argument is not supported anymore") - FORCE_INLINE bool set(const TValue& value, uint8_t) { - return _array.set(_index, value); - } - - private: - JsonArray& _array; - const size_t _index; -}; - -template -inline JsonArraySubscript JsonVariantSubscripts::operator[]( - size_t index) { - return impl()->template as()[index]; -} - -template -inline const JsonArraySubscript JsonVariantSubscripts::operator[]( - size_t index) const { - return impl()->template as()[index]; -} - -#if ARDUINOJSON_ENABLE_STD_STREAM -inline std::ostream& operator<<(std::ostream& os, - const JsonArraySubscript& source) { - return source.printTo(os); -} -#endif -} - -inline Internals::JsonArraySubscript JsonArray::operator[](size_t index) { - return Internals::JsonArraySubscript(*this, index); -} - -inline const Internals::JsonArraySubscript JsonArray::operator[]( - size_t index) const { - return Internals::JsonArraySubscript(*const_cast(this), index); -} -} - -#ifdef _MSC_VER -#pragma warning(pop) -#endif diff --git a/lib/ArduinoJson/src/ArduinoJson/JsonBuffer.hpp b/lib/ArduinoJson/src/ArduinoJson/JsonBuffer.hpp deleted file mode 100644 index 26101e08..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/JsonBuffer.hpp +++ /dev/null @@ -1,78 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#include // for size_t -#include // for uint8_t -#include - -#include "Data/NonCopyable.hpp" -#include "JsonVariant.hpp" -#include "TypeTraits/EnableIf.hpp" -#include "TypeTraits/IsArray.hpp" - -namespace ArduinoJson { -class JsonArray; -class JsonObject; - -// Entry point for using the library. -// -// Handle the memory management (done in derived classes) and calls the parser. -// This abstract class is implemented by StaticJsonBuffer which implements a -// fixed memory allocation. -class JsonBuffer : Internals::NonCopyable { - public: - // Allocates an empty JsonArray. - // - // Returns a reference to the new JsonArray or JsonArray::invalid() if the - // allocation fails. - JsonArray &createArray(); - - // Allocates an empty JsonObject. - // - // Returns a reference to the new JsonObject or JsonObject::invalid() if the - // allocation fails. - JsonObject &createObject(); - - // Duplicates a string - // - // const char* strdup(TValue); - // TValue = const std::string&, const String&, - template - DEPRECATED("char* are duplicated, you don't need strdup() anymore") - typename Internals::EnableIf::value, - const char *>::type strdup(const TString &src) { - return Internals::StringTraits::duplicate(src, this); - } - // - // const char* strdup(TValue); - // TValue = char*, const char*, const FlashStringHelper* - template - DEPRECATED("char* are duplicated, you don't need strdup() anymore") - const char *strdup(TString *src) { - return Internals::StringTraits::duplicate(src, this); - } - - // Allocates n bytes in the JsonBuffer. - // Return a pointer to the allocated memory or NULL if allocation fails. - virtual void *alloc(size_t size) = 0; - - protected: - // CAUTION: NO VIRTUAL DESTRUCTOR! - // If we add a virtual constructor the Arduino compiler will add malloc() - // and free() to the binary, adding 706 useless bytes. - ~JsonBuffer() {} - - // Preserve aligment if necessary - static FORCE_INLINE size_t round_size_up(size_t bytes) { -#if ARDUINOJSON_ENABLE_ALIGNMENT - const size_t x = sizeof(void *) - 1; - return (bytes + x) & ~x; -#else - return bytes; -#endif - } -}; -} diff --git a/lib/ArduinoJson/src/ArduinoJson/JsonBufferBase.hpp b/lib/ArduinoJson/src/ArduinoJson/JsonBufferBase.hpp deleted file mode 100644 index 1e771bfd..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/JsonBufferBase.hpp +++ /dev/null @@ -1,127 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#include "Deserialization/JsonParser.hpp" - -namespace ArduinoJson { -namespace Internals { -template -class JsonBufferBase : public JsonBuffer { - public: - // Allocates and populate a JsonArray from a JSON string. - // - // The First argument is a pointer to the JSON string, the memory must be - // writable - // because the parser will insert null-terminators and replace escaped chars. - // - // The second argument set the nesting limit - // - // Returns a reference to the new JsonObject or JsonObject::invalid() if the - // allocation fails. - // With this overload, the JsonBuffer will make a copy of the string - // - // JsonArray& parseArray(TString); - // TString = const std::string&, const String& - template - typename Internals::EnableIf::value, - JsonArray &>::type - parseArray(const TString &json, - uint8_t nestingLimit = ARDUINOJSON_DEFAULT_NESTING_LIMIT) { - return Internals::makeParser(that(), json, nestingLimit).parseArray(); - } - // - // JsonArray& parseArray(TString); - // TString = const char*, const char[N], const FlashStringHelper* - template - JsonArray &parseArray( - TString *json, uint8_t nestingLimit = ARDUINOJSON_DEFAULT_NESTING_LIMIT) { - return Internals::makeParser(that(), json, nestingLimit).parseArray(); - } - // - // JsonArray& parseArray(TString); - // TString = std::istream&, Stream& - template - JsonArray &parseArray( - TString &json, uint8_t nestingLimit = ARDUINOJSON_DEFAULT_NESTING_LIMIT) { - return Internals::makeParser(that(), json, nestingLimit).parseArray(); - } - - // Allocates and populate a JsonObject from a JSON string. - // - // The First argument is a pointer to the JSON string, the memory must be - // writable - // because the parser will insert null-terminators and replace escaped chars. - // - // The second argument set the nesting limit - // - // Returns a reference to the new JsonObject or JsonObject::invalid() if the - // allocation fails. - // - // JsonObject& parseObject(TString); - // TString = const std::string&, const String& - template - typename Internals::EnableIf::value, - JsonObject &>::type - parseObject(const TString &json, - uint8_t nestingLimit = ARDUINOJSON_DEFAULT_NESTING_LIMIT) { - return Internals::makeParser(that(), json, nestingLimit).parseObject(); - } - // - // JsonObject& parseObject(TString); - // TString = const char*, const char[N], const FlashStringHelper* - template - JsonObject &parseObject( - TString *json, uint8_t nestingLimit = ARDUINOJSON_DEFAULT_NESTING_LIMIT) { - return Internals::makeParser(that(), json, nestingLimit).parseObject(); - } - // - // JsonObject& parseObject(TString); - // TString = std::istream&, Stream& - template - JsonObject &parseObject( - TString &json, uint8_t nestingLimit = ARDUINOJSON_DEFAULT_NESTING_LIMIT) { - return Internals::makeParser(that(), json, nestingLimit).parseObject(); - } - - // Generalized version of parseArray() and parseObject(), also works for - // integral types. - // - // JsonVariant parse(TString); - // TString = const std::string&, const String& - template - typename Internals::EnableIf::value, - JsonVariant>::type - parse(const TString &json, - uint8_t nestingLimit = ARDUINOJSON_DEFAULT_NESTING_LIMIT) { - return Internals::makeParser(that(), json, nestingLimit).parseVariant(); - } - // - // JsonVariant parse(TString); - // TString = const char*, const char[N], const FlashStringHelper* - template - JsonVariant parse(TString *json, - uint8_t nestingLimit = ARDUINOJSON_DEFAULT_NESTING_LIMIT) { - return Internals::makeParser(that(), json, nestingLimit).parseVariant(); - } - // - // JsonVariant parse(TString); - // TString = std::istream&, Stream& - template - JsonVariant parse(TString &json, - uint8_t nestingLimit = ARDUINOJSON_DEFAULT_NESTING_LIMIT) { - return Internals::makeParser(that(), json, nestingLimit).parseVariant(); - } - - protected: - ~JsonBufferBase() {} - - private: - TDerived *that() { - return static_cast(this); - } -}; -} -} diff --git a/lib/ArduinoJson/src/ArduinoJson/JsonBufferImpl.hpp b/lib/ArduinoJson/src/ArduinoJson/JsonBufferImpl.hpp deleted file mode 100644 index cdea374b..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/JsonBufferImpl.hpp +++ /dev/null @@ -1,17 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#include "Deserialization/JsonParser.hpp" - -inline ArduinoJson::JsonArray &ArduinoJson::JsonBuffer::createArray() { - JsonArray *ptr = new (this) JsonArray(this); - return ptr ? *ptr : JsonArray::invalid(); -} - -inline ArduinoJson::JsonObject &ArduinoJson::JsonBuffer::createObject() { - JsonObject *ptr = new (this) JsonObject(this); - return ptr ? *ptr : JsonObject::invalid(); -} diff --git a/lib/ArduinoJson/src/ArduinoJson/JsonObject.hpp b/lib/ArduinoJson/src/ArduinoJson/JsonObject.hpp deleted file mode 100644 index caf698a3..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/JsonObject.hpp +++ /dev/null @@ -1,328 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#include "Data/JsonBufferAllocated.hpp" -#include "Data/List.hpp" -#include "Data/ReferenceType.hpp" -#include "Data/ValueSaver.hpp" -#include "JsonPair.hpp" -#include "Serialization/JsonPrintable.hpp" -#include "StringTraits/StringTraits.hpp" -#include "TypeTraits/EnableIf.hpp" -#include "TypeTraits/IsArray.hpp" -#include "TypeTraits/IsFloatingPoint.hpp" -#include "TypeTraits/IsSame.hpp" - -// Returns the size (in bytes) of an object with n elements. -// Can be very handy to determine the size of a StaticJsonBuffer. -#define JSON_OBJECT_SIZE(NUMBER_OF_ELEMENTS) \ - (sizeof(JsonObject) + (NUMBER_OF_ELEMENTS) * sizeof(JsonObject::node_type)) - -namespace ArduinoJson { - -// Forward declarations -class JsonArray; -class JsonBuffer; -namespace Internals { -template -class JsonObjectSubscript; -} - -// A dictionary of JsonVariant indexed by string (char*) -// -// The constructor is private, instances must be created via -// JsonBuffer::createObject() or JsonBuffer::parseObject(). -// A JsonObject can be serialized to a JSON string via JsonObject::printTo(). -// It can also be deserialized from a JSON string via JsonBuffer::parseObject(). -class JsonObject : public Internals::JsonPrintable, - public Internals::ReferenceType, - public Internals::NonCopyable, - public Internals::List, - public Internals::JsonBufferAllocated { - public: - // Create an empty JsonArray attached to the specified JsonBuffer. - // You should not use this constructor directly. - // Instead, use JsonBuffer::createObject() or JsonBuffer.parseObject(). - explicit JsonObject(JsonBuffer* buffer) throw() - : Internals::List(buffer) {} - - // Gets or sets the value associated with the specified key. - // - // JsonObjectSubscript operator[](TKey) - // TKey = const std::string&, const String& - template - Internals::JsonObjectSubscript operator[]( - const TString& key) { - return Internals::JsonObjectSubscript(*this, key); - } - // - // JsonObjectSubscript operator[](TKey) - // TKey = char*, const char*, char[], const char[N], const FlashStringHelper* - template - Internals::JsonObjectSubscript operator[](TString* key) { - return Internals::JsonObjectSubscript(*this, key); - } - - // Gets the value associated with the specified key. - // - // const JsonObjectSubscript operator[](TKey) const; - // TKey = const std::string&, const String& - template - const Internals::JsonObjectSubscript operator[]( - const TString& key) const { - return Internals::JsonObjectSubscript( - *const_cast(this), key); - } - // - // const JsonObjectSubscript operator[](TKey) const; - // TKey = const char*, const char[N], const FlashStringHelper* - template - const Internals::JsonObjectSubscript operator[]( - TString* key) const { - return Internals::JsonObjectSubscript( - *const_cast(this), key); - } - - // Sets the specified key with the specified value. - // - // bool set(TKey, TValue); - // TKey = const std::string&, const String& - // TValue = bool, long, int, short, float, double, RawJson, JsonVariant, - // std::string, String, JsonArray, JsonObject - template - bool set(const TString& key, const TValue& value) { - return set_impl(key, value); - } - // - // bool set(TKey, TValue); - // TKey = const std::string&, const String& - // TValue = char*, const char*, const FlashStringHelper* - template - bool set(const TString& key, TValue* value) { - return set_impl(key, value); - } - // - // bool set(TKey, const TValue&); - // TKey = char*, const char*, const FlashStringHelper* - // TValue = bool, long, int, short, float, double, RawJson, JsonVariant, - // std::string, String, JsonArray, JsonObject - template - bool set(TString* key, const TValue& value) { - return set_impl(key, value); - } - // - // bool set(TKey, TValue); - // TKey = char*, const char*, const FlashStringHelper* - // TValue = char*, const char*, const FlashStringHelper* - template - bool set(TString* key, TValue* value) { - return set_impl(key, value); - } - // - // bool set(TKey, TValue, uint8_t decimals); - // TKey = const std::string&, const String& - // TValue = float, double - template - DEPRECATED("Second argument is not supported anymore") - typename Internals::EnableIf::value, - bool>::type - set(const TString& key, TValue value, uint8_t) { - return set_impl(key, - JsonVariant(value)); - } - // - // bool set(TKey, TValue, uint8_t decimals); - // TKey = char*, const char*, const FlashStringHelper* - // TValue = float, double - template - DEPRECATED("Second argument is not supported anymore") - typename Internals::EnableIf::value, - bool>::type - set(TString* key, TValue value, uint8_t) { - return set_impl(key, JsonVariant(value)); - } - - // Gets the value associated with the specified key. - // - // TValue get(TKey) const; - // TKey = const std::string&, const String& - // TValue = bool, char, long, int, short, float, double, - // std::string, String, JsonArray, JsonObject - template - typename Internals::JsonVariantAs::type get( - const TString& key) const { - return get_impl(key); - } - // - // TValue get(TKey) const; - // TKey = char*, const char*, const FlashStringHelper* - // TValue = bool, char, long, int, short, float, double, - // std::string, String, JsonArray, JsonObject - template - typename Internals::JsonVariantAs::type get(TString* key) const { - return get_impl(key); - } - - // Checks the type of the value associated with the specified key. - // - // - // bool is(TKey) const; - // TKey = const std::string&, const String& - // TValue = bool, char, long, int, short, float, double, - // std::string, String, JsonArray, JsonObject - template - bool is(const TString& key) const { - return is_impl(key); - } - // - // bool is(TKey) const; - // TKey = char*, const char*, const FlashStringHelper* - // TValue = bool, char, long, int, short, float, double, - // std::string, String, JsonArray, JsonObject - template - bool is(TString* key) const { - return is_impl(key); - } - - // Creates and adds a JsonArray. - // - // JsonArray& createNestedArray(TKey); - // TKey = const std::string&, const String& - template - JsonArray& createNestedArray(const TString& key) { - return createNestedArray_impl(key); - } - // JsonArray& createNestedArray(TKey); - // TKey = char*, const char*, char[], const char[], const FlashStringHelper* - template - JsonArray& createNestedArray(TString* key) { - return createNestedArray_impl(key); - } - - // Creates and adds a JsonObject. - // - // JsonObject& createNestedObject(TKey); - // TKey = const std::string&, const String& - template - JsonObject& createNestedObject(const TString& key) { - return createNestedObject_impl(key); - } - // - // JsonObject& createNestedObject(TKey); - // TKey = char*, const char*, char[], const char[], const FlashStringHelper* - template - JsonObject& createNestedObject(TString* key) { - return createNestedObject_impl(key); - } - - // Tells weither the specified key is present and associated with a value. - // - // bool containsKey(TKey); - // TKey = const std::string&, const String& - template - bool containsKey(const TString& key) const { - return findKey(key) != end(); - } - // - // bool containsKey(TKey); - // TKey = char*, const char*, char[], const char[], const FlashStringHelper* - template - bool containsKey(TString* key) const { - return findKey(key) != end(); - } - - // Removes the specified key and the associated value. - // - // void remove(TKey); - // TKey = const std::string&, const String& - template - void remove(const TString& key) { - remove(findKey(key)); - } - // - // void remove(TKey); - // TKey = char*, const char*, char[], const char[], const FlashStringHelper* - template - void remove(TString* key) { - remove(findKey(key)); - } - // - // void remove(iterator) - using Internals::List::remove; - - // Returns a reference an invalid JsonObject. - // This object is meant to replace a NULL pointer. - // This is used when memory allocation or JSON parsing fail. - static JsonObject& invalid() { - static JsonObject instance(NULL); - return instance; - } - - private: - // Returns the list node that matches the specified key. - template - iterator findKey(TStringRef key) { - iterator it; - for (it = begin(); it != end(); ++it) { - if (Internals::StringTraits::equals(key, it->key)) break; - } - return it; - } - template - const_iterator findKey(TStringRef key) const { - return const_cast(this)->findKey(key); - } - - template - typename Internals::JsonVariantAs::type get_impl( - TStringRef key) const { - const_iterator it = findKey(key); - return it != end() ? it->value.as() - : Internals::JsonVariantDefault::get(); - } - - template - bool set_impl(TStringRef key, TValueRef value) { - // ignore null key - if (Internals::StringTraits::is_null(key)) return false; - - // search a matching key - iterator it = findKey(key); - if (it == end()) { - // add the key - it = Internals::List::add(); - if (it == end()) return false; - bool key_ok = - Internals::ValueSaver::save(_buffer, it->key, key); - if (!key_ok) return false; - } - - // save the value - return Internals::ValueSaver::save(_buffer, it->value, value); - } - - template - bool is_impl(TStringRef key) const { - const_iterator it = findKey(key); - return it != end() ? it->value.is() : false; - } - - template - JsonArray& createNestedArray_impl(TStringRef key); - - template - JsonObject& createNestedObject_impl(TStringRef key); -}; - -namespace Internals { -template <> -struct JsonVariantDefault { - static JsonObject& get() { - return JsonObject::invalid(); - } -}; -} // namespace Internals -} // namespace ArduinoJson diff --git a/lib/ArduinoJson/src/ArduinoJson/JsonObjectImpl.hpp b/lib/ArduinoJson/src/ArduinoJson/JsonObjectImpl.hpp deleted file mode 100644 index e7689b50..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/JsonObjectImpl.hpp +++ /dev/null @@ -1,28 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#include "JsonArray.hpp" -#include "JsonObject.hpp" -#include "JsonObjectSubscript.hpp" - -namespace ArduinoJson { - -template -inline JsonArray &JsonObject::createNestedArray_impl(TStringRef key) { - if (!_buffer) return JsonArray::invalid(); - JsonArray &array = _buffer->createArray(); - set(key, array); - return array; -} - -template -inline JsonObject &JsonObject::createNestedObject_impl(TStringRef key) { - if (!_buffer) return JsonObject::invalid(); - JsonObject &object = _buffer->createObject(); - set(key, object); - return object; -} -} diff --git a/lib/ArduinoJson/src/ArduinoJson/JsonObjectSubscript.hpp b/lib/ArduinoJson/src/ArduinoJson/JsonObjectSubscript.hpp deleted file mode 100644 index 6ac47637..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/JsonObjectSubscript.hpp +++ /dev/null @@ -1,110 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#include "Configuration.hpp" -#include "JsonVariantBase.hpp" -#include "TypeTraits/EnableIf.hpp" - -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable : 4522) -#endif - -namespace ArduinoJson { -namespace Internals { - -template -class JsonObjectSubscript - : public JsonVariantBase > { - typedef JsonObjectSubscript this_type; - - public: - FORCE_INLINE JsonObjectSubscript(JsonObject& object, TStringRef key) - : _object(object), _key(key) {} - - FORCE_INLINE this_type& operator=(const this_type& src) { - _object.set(_key, src); - return *this; - } - - // Set the specified value - // - // operator=(const TValue&); - // TValue = bool, char, long, int, short, float, double, - // std::string, String, JsonArray, JsonObject - template - FORCE_INLINE typename EnableIf::value, this_type&>::type - operator=(const TValue& src) { - _object.set(_key, src); - return *this; - } - // - // operator=(TValue); - // TValue = char*, const char*, const FlashStringHelper* - template - FORCE_INLINE this_type& operator=(TValue* src) { - _object.set(_key, src); - return *this; - } - - FORCE_INLINE bool success() const { - return _object.containsKey(_key); - } - - template - FORCE_INLINE typename JsonVariantAs::type as() const { - return _object.get(_key); - } - - template - FORCE_INLINE bool is() const { - return _object.is(_key); - } - - // Sets the specified value. - // - // bool set(const TValue&); - // TValue = bool, char, long, int, short, float, double, RawJson, JsonVariant, - // std::string, String, JsonArray, JsonObject - template - FORCE_INLINE typename EnableIf::value, bool>::type set( - const TValue& value) { - return _object.set(_key, value); - } - // - // bool set(TValue); - // TValue = char*, const char, const FlashStringHelper* - template - FORCE_INLINE bool set(const TValue* value) { - return _object.set(_key, value); - } - // - // bool set(TValue, uint8_t decimals); - // TValue = float, double - template - DEPRECATED("Second argument is not supported anymore") - FORCE_INLINE bool set(const TValue& value, uint8_t) { - return _object.set(_key, value); - } - - private: - JsonObject& _object; - TStringRef _key; -}; - -#if ARDUINOJSON_ENABLE_STD_STREAM -template -inline std::ostream& operator<<(std::ostream& os, - const JsonObjectSubscript& source) { - return source.printTo(os); -} -#endif -} -} - -#ifdef _MSC_VER -#pragma warning(pop) -#endif diff --git a/lib/ArduinoJson/src/ArduinoJson/JsonPair.hpp b/lib/ArduinoJson/src/ArduinoJson/JsonPair.hpp deleted file mode 100644 index 41724304..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/JsonPair.hpp +++ /dev/null @@ -1,16 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#include "JsonVariant.hpp" - -namespace ArduinoJson { - -// A key value pair for JsonObject. -struct JsonPair { - const char* key; - JsonVariant value; -}; -} diff --git a/lib/ArduinoJson/src/ArduinoJson/JsonVariant.hpp b/lib/ArduinoJson/src/ArduinoJson/JsonVariant.hpp deleted file mode 100644 index 43c51b77..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/JsonVariant.hpp +++ /dev/null @@ -1,357 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#include -#include // for uint8_t - -#include "Data/JsonVariantContent.hpp" -#include "Data/JsonVariantDefault.hpp" -#include "Data/JsonVariantType.hpp" -#include "JsonVariantBase.hpp" -#include "RawJson.hpp" -#include "Serialization/JsonPrintable.hpp" -#include "TypeTraits/EnableIf.hpp" -#include "TypeTraits/IsChar.hpp" -#include "TypeTraits/IsFloatingPoint.hpp" -#include "TypeTraits/IsIntegral.hpp" -#include "TypeTraits/IsSame.hpp" -#include "TypeTraits/IsSignedIntegral.hpp" -#include "TypeTraits/IsUnsignedIntegral.hpp" -#include "TypeTraits/RemoveConst.hpp" -#include "TypeTraits/RemoveReference.hpp" - -namespace ArduinoJson { - -// Forward declarations. -class JsonArray; -class JsonObject; - -// A variant that can be a any value serializable to a JSON value. -// -// It can be set to: -// - a boolean -// - a char, short, int or a long (signed or unsigned) -// - a string (const char*) -// - a reference to a JsonArray or JsonObject -class JsonVariant : public Internals::JsonVariantBase { - template - friend class Internals::JsonSerializer; - - public: - // Creates an uninitialized JsonVariant - JsonVariant() : _type(Internals::JSON_UNDEFINED) {} - - // Create a JsonVariant containing a boolean value. - // It will be serialized as "true" or "false" in JSON. - JsonVariant(bool value) { - using namespace Internals; - _type = JSON_BOOLEAN; - _content.asInteger = static_cast(value); - } - - // Create a JsonVariant containing a floating point value. - // JsonVariant(double value); - // JsonVariant(float value); - template - JsonVariant(T value, typename Internals::EnableIf< - Internals::IsFloatingPoint::value>::type * = 0) { - using namespace Internals; - _type = JSON_FLOAT; - _content.asFloat = static_cast(value); - } - template - DEPRECATED("Second argument is not supported anymore") - JsonVariant(T value, uint8_t, - typename Internals::EnableIf< - Internals::IsFloatingPoint::value>::type * = 0) { - using namespace Internals; - _type = JSON_FLOAT; - _content.asFloat = static_cast(value); - } - - // Create a JsonVariant containing an integer value. - // JsonVariant(char) - // JsonVariant(signed short) - // JsonVariant(signed int) - // JsonVariant(signed long) - // JsonVariant(signed char) - template - JsonVariant( - T value, - typename Internals::EnableIf::value || - Internals::IsSame::value>::type * = - 0) { - using namespace Internals; - if (value >= 0) { - _type = JSON_POSITIVE_INTEGER; - _content.asInteger = static_cast(value); - } else { - _type = JSON_NEGATIVE_INTEGER; - _content.asInteger = static_cast(-value); - } - } - // JsonVariant(unsigned short) - // JsonVariant(unsigned int) - // JsonVariant(unsigned long) - template - JsonVariant(T value, - typename Internals::EnableIf< - Internals::IsUnsignedIntegral::value>::type * = 0) { - using namespace Internals; - _type = JSON_POSITIVE_INTEGER; - _content.asInteger = static_cast(value); - } - - // Create a JsonVariant containing a string. - // JsonVariant(const char*); - // JsonVariant(const signed char*); - // JsonVariant(const unsigned char*); - template - JsonVariant( - const TChar *value, - typename Internals::EnableIf::value>::type * = - 0) { - _type = Internals::JSON_STRING; - _content.asString = reinterpret_cast(value); - } - - // Create a JsonVariant containing an unparsed string - JsonVariant(Internals::RawJsonString value) { - _type = Internals::JSON_UNPARSED; - _content.asString = value; - } - - // Create a JsonVariant containing a reference to an array. - // CAUTION: we are lying about constness, because the array can be modified if - // the variant is converted back to a JsonArray& - JsonVariant(const JsonArray &array); - - // Create a JsonVariant containing a reference to an object. - // CAUTION: we are lying about constness, because the object can be modified - // if the variant is converted back to a JsonObject& - JsonVariant(const JsonObject &object); - - // Get the variant as the specified type. - // - // char as() const; - // signed char as() const; - // signed short as() const; - // signed int as() const; - // signed long as() const; - // unsigned char as() const; - // unsigned short as() const; - // unsigned int as() const; - // unsigned long as() const; - template - const typename Internals::EnableIf::value, T>::type - as() const { - return variantAsInteger(); - } - // bool as() const - template - const typename Internals::EnableIf::value, T>::type - as() const { - return variantAsInteger() != 0; - } - // - // double as() const; - // float as() const; - template - const typename Internals::EnableIf::value, - T>::type - as() const { - return variantAsFloat(); - } - // - // const char* as() const; - // const char* as() const; - template - typename Internals::EnableIf::value || - Internals::IsSame::value, - const char *>::type - as() const { - return variantAsString(); - } - // - // std::string as() const; - // String as() const; - template - typename Internals::EnableIf::has_append, T>::type - as() const { - const char *cstr = variantAsString(); - if (cstr) return T(cstr); - T s; - printTo(s); - return s; - } - // - // JsonArray& as const; - // JsonArray& as const; - template - typename Internals::EnableIf< - Internals::IsSame::type, - JsonArray>::value, - JsonArray &>::type - as() const { - return variantAsArray(); - } - // - // const JsonArray& as const; - template - typename Internals::EnableIf< - Internals::IsSame::type, - const JsonArray>::value, - const JsonArray &>::type - as() const { - return variantAsArray(); - } - // - // JsonObject& as const; - // JsonObject& as const; - template - typename Internals::EnableIf< - Internals::IsSame::type, - JsonObject>::value, - JsonObject &>::type - as() const { - return variantAsObject(); - } - // - // JsonObject& as const; - // JsonObject& as const; - template - typename Internals::EnableIf< - Internals::IsSame::type, - const JsonObject>::value, - const JsonObject &>::type - as() const { - return variantAsObject(); - } - // - // JsonVariant as const; - template - typename Internals::EnableIf::value, - T>::type - as() const { - return *this; - } - - // Tells weither the variant has the specified type. - // Returns true if the variant has type type T, false otherwise. - // - // bool is() const; - // bool is() const; - // bool is() const; - // bool is() const; - // bool is() const; - // bool is() const; - // bool is() const; - // bool is() const; - // bool is() const; - template - typename Internals::EnableIf::value, bool>::type is() - const { - return variantIsInteger(); - } - // - // bool is() const; - // bool is() const; - template - typename Internals::EnableIf::value, bool>::type - is() const { - return variantIsFloat(); - } - // - // bool is() const - template - typename Internals::EnableIf::value, bool>::type - is() const { - return variantIsBoolean(); - } - // - // bool is() const; - // bool is() const; - // bool is() const; - template - typename Internals::EnableIf::value || - Internals::IsSame::value || - Internals::StringTraits::has_append, - bool>::type - is() const { - return variantIsString(); - } - // - // bool is const; - // bool is const; - // bool is const; - template - typename Internals::EnableIf< - Internals::IsSame::type>::type, - JsonArray>::value, - bool>::type - is() const { - return variantIsArray(); - } - // - // bool is const; - // bool is const; - // bool is const; - template - typename Internals::EnableIf< - Internals::IsSame::type>::type, - JsonObject>::value, - bool>::type - is() const { - return variantIsObject(); - } - - // Returns true if the variant has a value - bool success() const { - return _type != Internals::JSON_UNDEFINED; - } - - private: - JsonArray &variantAsArray() const; - JsonObject &variantAsObject() const; - const char *variantAsString() const; - template - T variantAsFloat() const; - template - T variantAsInteger() const; - bool variantIsBoolean() const; - bool variantIsFloat() const; - bool variantIsInteger() const; - bool variantIsArray() const { - return _type == Internals::JSON_ARRAY; - } - bool variantIsObject() const { - return _type == Internals::JSON_OBJECT; - } - bool variantIsString() const { - return _type == Internals::JSON_STRING || - (_type == Internals::JSON_UNPARSED && _content.asString && - !strcmp("null", _content.asString)); - } - - // The current type of the variant - Internals::JsonVariantType _type; - - // The various alternatives for the value of the variant. - Internals::JsonVariantContent _content; -}; - -DEPRECATED("Decimal places are ignored, use the float value instead") -inline JsonVariant float_with_n_digits(float value, uint8_t) { - return JsonVariant(value); -} - -DEPRECATED("Decimal places are ignored, use the double value instead") -inline JsonVariant double_with_n_digits(double value, uint8_t) { - return JsonVariant(value); -} -} // namespace ArduinoJson diff --git a/lib/ArduinoJson/src/ArduinoJson/JsonVariantBase.hpp b/lib/ArduinoJson/src/ArduinoJson/JsonVariantBase.hpp deleted file mode 100644 index 44acf2e1..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/JsonVariantBase.hpp +++ /dev/null @@ -1,24 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#include "JsonVariantCasts.hpp" -#include "JsonVariantComparisons.hpp" -#include "JsonVariantOr.hpp" -#include "JsonVariantSubscripts.hpp" -#include "Serialization/JsonPrintable.hpp" - -namespace ArduinoJson { -namespace Internals { - -template -class JsonVariantBase : public JsonPrintable, - public JsonVariantCasts, - public JsonVariantComparisons, - public JsonVariantOr, - public JsonVariantSubscripts, - public JsonVariantTag {}; -} -} diff --git a/lib/ArduinoJson/src/ArduinoJson/JsonVariantCasts.hpp b/lib/ArduinoJson/src/ArduinoJson/JsonVariantCasts.hpp deleted file mode 100644 index 68f5bd7d..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/JsonVariantCasts.hpp +++ /dev/null @@ -1,59 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#include "Data/JsonVariantAs.hpp" -#include "Polyfills/attributes.hpp" - -namespace ArduinoJson { -namespace Internals { - -template -class JsonVariantCasts { - public: -#if ARDUINOJSON_ENABLE_DEPRECATED - DEPRECATED("use as() instead") - FORCE_INLINE JsonArray &asArray() const { - return impl()->template as(); - } - - DEPRECATED("use as() instead") - FORCE_INLINE JsonObject &asObject() const { - return impl()->template as(); - } - - DEPRECATED("use as() instead") - FORCE_INLINE const char *asString() const { - return impl()->template as(); - } -#endif - - // Gets the variant as an array. - // Returns a reference to the JsonArray or JsonArray::invalid() if the - // variant - // is not an array. - FORCE_INLINE operator JsonArray &() const { - return impl()->template as(); - } - - // Gets the variant as an object. - // Returns a reference to the JsonObject or JsonObject::invalid() if the - // variant is not an object. - FORCE_INLINE operator JsonObject &() const { - return impl()->template as(); - } - - template - FORCE_INLINE operator T() const { - return impl()->template as(); - } - - private: - const TImpl *impl() const { - return static_cast(this); - } -}; -} -} diff --git a/lib/ArduinoJson/src/ArduinoJson/JsonVariantComparisons.hpp b/lib/ArduinoJson/src/ArduinoJson/JsonVariantComparisons.hpp deleted file mode 100644 index 47f9d632..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/JsonVariantComparisons.hpp +++ /dev/null @@ -1,139 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#include "StringTraits/StringTraits.hpp" -#include "TypeTraits/EnableIf.hpp" -#include "TypeTraits/IsVariant.hpp" - -namespace ArduinoJson { -namespace Internals { - -template -class JsonVariantComparisons { - public: - template - friend bool operator==(const JsonVariantComparisons &variant, - TComparand comparand) { - return variant.equals(comparand); - } - - template - friend typename EnableIf::value, bool>::type - operator==(TComparand comparand, const JsonVariantComparisons &variant) { - return variant.equals(comparand); - } - - template - friend bool operator!=(const JsonVariantComparisons &variant, - TComparand comparand) { - return !variant.equals(comparand); - } - - template - friend typename EnableIf::value, bool>::type - operator!=(TComparand comparand, const JsonVariantComparisons &variant) { - return !variant.equals(comparand); - } - - template - friend bool operator<=(const JsonVariantComparisons &left, TComparand right) { - return left.as() <= right; - } - - template - friend bool operator<=(TComparand comparand, - const JsonVariantComparisons &variant) { - return comparand <= variant.as(); - } - - template - friend bool operator>=(const JsonVariantComparisons &variant, - TComparand comparand) { - return variant.as() >= comparand; - } - - template - friend bool operator>=(TComparand comparand, - const JsonVariantComparisons &variant) { - return comparand >= variant.as(); - } - - template - friend bool operator<(const JsonVariantComparisons &varian, - TComparand comparand) { - return varian.as() < comparand; - } - - template - friend bool operator<(TComparand comparand, - const JsonVariantComparisons &variant) { - return comparand < variant.as(); - } - - template - friend bool operator>(const JsonVariantComparisons &variant, - TComparand comparand) { - return variant.as() > comparand; - } - - template - friend bool operator>(TComparand comparand, - const JsonVariantComparisons &variant) { - return comparand > variant.as(); - } - - private: - const TImpl *impl() const { - return static_cast(this); - } - - template - const typename JsonVariantAs::type as() const { - return impl()->template as(); - } - - template - bool is() const { - return impl()->template is(); - } - - template - typename EnableIf::has_equals, bool>::type equals( - const TString &comparand) const { - const char *value = as(); - return StringTraits::equals(comparand, value); - } - - template - typename EnableIf::value && - !StringTraits::has_equals, - bool>::type - equals(const TComparand &comparand) const { - return as() == comparand; - } - - template - bool equals(const JsonVariantComparisons &right) const { - using namespace Internals; - if (is() && right.template is()) - return as() == right.template as(); - if (is() && right.template is()) - return as() == right.template as(); - if (is() && right.template is()) - return as() == right.template as(); - if (is() && right.template is()) - return as() == right.template as(); - if (is() && right.template is()) - return as() == right.template as(); - if (is() && right.template is()) - return StringTraits::equals(as(), - right.template as()); - - return false; - } -}; -} // namespace Internals -} // namespace ArduinoJson diff --git a/lib/ArduinoJson/src/ArduinoJson/JsonVariantImpl.hpp b/lib/ArduinoJson/src/ArduinoJson/JsonVariantImpl.hpp deleted file mode 100644 index 31f96ce1..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/JsonVariantImpl.hpp +++ /dev/null @@ -1,126 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#include "Configuration.hpp" -#include "JsonArray.hpp" -#include "JsonObject.hpp" -#include "JsonVariant.hpp" -#include "Polyfills/isFloat.hpp" -#include "Polyfills/isInteger.hpp" -#include "Polyfills/parseFloat.hpp" -#include "Polyfills/parseInteger.hpp" - -#include // for strcmp - -namespace ArduinoJson { - -inline JsonVariant::JsonVariant(const JsonArray &array) { - if (array.success()) { - _type = Internals::JSON_ARRAY; - _content.asArray = const_cast(&array); - } else { - _type = Internals::JSON_UNDEFINED; - } -} - -inline JsonVariant::JsonVariant(const JsonObject &object) { - if (object.success()) { - _type = Internals::JSON_OBJECT; - _content.asObject = const_cast(&object); - } else { - _type = Internals::JSON_UNDEFINED; - } -} - -inline JsonArray &JsonVariant::variantAsArray() const { - if (_type == Internals::JSON_ARRAY) return *_content.asArray; - return JsonArray::invalid(); -} - -inline JsonObject &JsonVariant::variantAsObject() const { - if (_type == Internals::JSON_OBJECT) return *_content.asObject; - return JsonObject::invalid(); -} - -template -inline T JsonVariant::variantAsInteger() const { - using namespace Internals; - switch (_type) { - case JSON_UNDEFINED: - return 0; - case JSON_POSITIVE_INTEGER: - case JSON_BOOLEAN: - return T(_content.asInteger); - case JSON_NEGATIVE_INTEGER: - return T(~_content.asInteger + 1); - case JSON_STRING: - case JSON_UNPARSED: - return parseInteger(_content.asString); - default: - return T(_content.asFloat); - } -} - -inline const char *JsonVariant::variantAsString() const { - using namespace Internals; - if (_type == JSON_UNPARSED && _content.asString && - !strcmp("null", _content.asString)) - return NULL; - if (_type == JSON_STRING || _type == JSON_UNPARSED) return _content.asString; - return NULL; -} - -template -inline T JsonVariant::variantAsFloat() const { - using namespace Internals; - switch (_type) { - case JSON_UNDEFINED: - return 0; - case JSON_POSITIVE_INTEGER: - case JSON_BOOLEAN: - return static_cast(_content.asInteger); - case JSON_NEGATIVE_INTEGER: - return -static_cast(_content.asInteger); - case JSON_STRING: - case JSON_UNPARSED: - return parseFloat(_content.asString); - default: - return static_cast(_content.asFloat); - } -} - -inline bool JsonVariant::variantIsBoolean() const { - using namespace Internals; - if (_type == JSON_BOOLEAN) return true; - - if (_type != JSON_UNPARSED || _content.asString == NULL) return false; - - return !strcmp(_content.asString, "true") || - !strcmp(_content.asString, "false"); -} - -inline bool JsonVariant::variantIsInteger() const { - using namespace Internals; - - return _type == JSON_POSITIVE_INTEGER || _type == JSON_NEGATIVE_INTEGER || - (_type == JSON_UNPARSED && isInteger(_content.asString)); -} - -inline bool JsonVariant::variantIsFloat() const { - using namespace Internals; - - return _type == JSON_FLOAT || _type == JSON_POSITIVE_INTEGER || - _type == JSON_NEGATIVE_INTEGER || - (_type == JSON_UNPARSED && isFloat(_content.asString)); -} - -#if ARDUINOJSON_ENABLE_STD_STREAM -inline std::ostream &operator<<(std::ostream &os, const JsonVariant &source) { - return source.printTo(os); -} -#endif - -} // namespace ArduinoJson diff --git a/lib/ArduinoJson/src/ArduinoJson/JsonVariantOr.hpp b/lib/ArduinoJson/src/ArduinoJson/JsonVariantOr.hpp deleted file mode 100644 index d8022fcb..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/JsonVariantOr.hpp +++ /dev/null @@ -1,52 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#include "Data/JsonVariantAs.hpp" -#include "Polyfills/attributes.hpp" -#include "TypeTraits/EnableIf.hpp" -#include "TypeTraits/IsIntegral.hpp" - -namespace ArduinoJson { -namespace Internals { - -template -class JsonVariantOr { - public: - // Returns the default value if the JsonVariant is undefined of incompatible - template - typename EnableIf::value, T>::type operator|( - const T &defaultValue) const { - if (impl()->template is()) - return impl()->template as(); - else - return defaultValue; - } - - // Returns the default value if the JsonVariant is undefined of incompatible - // Special case for string: null is treated as undefined - const char *operator|(const char *defaultValue) const { - const char *value = impl()->template as(); - return value ? value : defaultValue; - } - - // Returns the default value if the JsonVariant is undefined of incompatible - // Special case for integers: we also accept double - template - typename EnableIf::value, Integer>::type operator|( - const Integer &defaultValue) const { - if (impl()->template is()) - return impl()->template as(); - else - return defaultValue; - } - - private: - const TImpl *impl() const { - return static_cast(this); - } -}; -} // namespace Internals -} // namespace ArduinoJson diff --git a/lib/ArduinoJson/src/ArduinoJson/JsonVariantSubscripts.hpp b/lib/ArduinoJson/src/ArduinoJson/JsonVariantSubscripts.hpp deleted file mode 100644 index 279ee019..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/JsonVariantSubscripts.hpp +++ /dev/null @@ -1,86 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#include "Data/JsonVariantAs.hpp" -#include "Polyfills/attributes.hpp" -#include "StringTraits/StringTraits.hpp" -#include "TypeTraits/EnableIf.hpp" - -namespace ArduinoJson { -namespace Internals { - -// Forward declarations. -class JsonArraySubscript; -template -class JsonObjectSubscript; - -template -class JsonVariantSubscripts { - public: - // Mimics an array or an object. - // Returns the size of the array or object if the variant has that type. - // Returns 0 if the variant is neither an array nor an object - size_t size() const { - return impl()->template as().size() + - impl()->template as().size(); - } - - // Mimics an array. - // Returns the element at specified index if the variant is an array. - // Returns JsonVariant::invalid() if the variant is not an array. - FORCE_INLINE const JsonArraySubscript operator[](size_t index) const; - FORCE_INLINE JsonArraySubscript operator[](size_t index); - - // Mimics an object. - // Returns the value associated with the specified key if the variant is - // an object. - // Return JsonVariant::invalid() if the variant is not an object. - // - // const JsonObjectSubscript operator[](TKey) const; - // TKey = const std::string&, const String& - template - FORCE_INLINE - typename EnableIf::has_equals, - const JsonObjectSubscript >::type - operator[](const TString &key) const { - return impl()->template as()[key]; - } - // - // const JsonObjectSubscript operator[](TKey) const; - // TKey = const std::string&, const String& - template - FORCE_INLINE typename EnableIf::has_equals, - JsonObjectSubscript >::type - operator[](const TString &key) { - return impl()->template as()[key]; - } - // - // JsonObjectSubscript operator[](TKey); - // TKey = const char*, const char[N], const FlashStringHelper* - template - FORCE_INLINE typename EnableIf::has_equals, - JsonObjectSubscript >::type - operator[](const TString *key) { - return impl()->template as()[key]; - } - // - // JsonObjectSubscript operator[](TKey); - // TKey = const char*, const char[N], const FlashStringHelper* - template - FORCE_INLINE - typename EnableIf::has_equals, - const JsonObjectSubscript >::type - operator[](const TString *key) const { - return impl()->template as()[key]; - } - - private: - const TImpl *impl() const { - return static_cast(this); - } -}; -} -} diff --git a/lib/ArduinoJson/src/ArduinoJson/Polyfills/attributes.hpp b/lib/ArduinoJson/src/ArduinoJson/Polyfills/attributes.hpp deleted file mode 100644 index b49091dd..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/Polyfills/attributes.hpp +++ /dev/null @@ -1,29 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#ifdef _MSC_VER // Visual Studio - -#define FORCE_INLINE // __forceinline causes C4714 when returning std::string -#define NO_INLINE __declspec(noinline) -#define DEPRECATED(msg) __declspec(deprecated(msg)) - -#elif defined(__GNUC__) // GCC or Clang - -#define FORCE_INLINE __attribute__((always_inline)) -#define NO_INLINE __attribute__((noinline)) -#if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5) -#define DEPRECATED(msg) __attribute__((deprecated(msg))) -#else -#define DEPRECATED(msg) __attribute__((deprecated)) -#endif - -#else // Other compilers - -#define FORCE_INLINE -#define NO_INLINE -#define DEPRECATED(msg) - -#endif diff --git a/lib/ArduinoJson/src/ArduinoJson/Polyfills/ctype.hpp b/lib/ArduinoJson/src/ArduinoJson/Polyfills/ctype.hpp deleted file mode 100644 index 2d52703c..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/Polyfills/ctype.hpp +++ /dev/null @@ -1,18 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -namespace ArduinoJson { -namespace Internals { - -inline bool isdigit(char c) { - return '0' <= c && c <= '9'; -} - -inline bool issign(char c) { - return '-' == c || c == '+'; -} -} -} diff --git a/lib/ArduinoJson/src/ArduinoJson/Polyfills/isFloat.hpp b/lib/ArduinoJson/src/ArduinoJson/Polyfills/isFloat.hpp deleted file mode 100644 index 973b89fe..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/Polyfills/isFloat.hpp +++ /dev/null @@ -1,38 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#include // for strcmp -#include "./ctype.hpp" - -namespace ArduinoJson { -namespace Internals { - -inline bool isFloat(const char* s) { - if (!s) return false; - - if (!strcmp(s, "NaN")) return true; - if (issign(*s)) s++; - if (!strcmp(s, "Infinity")) return true; - if (*s == '\0') return false; - - while (isdigit(*s)) s++; - - if (*s == '.') { - s++; - while (isdigit(*s)) s++; - } - - if (*s == 'e' || *s == 'E') { - s++; - if (issign(*s)) s++; - if (!isdigit(*s)) return false; - while (isdigit(*s)) s++; - } - - return *s == '\0'; -} -} -} diff --git a/lib/ArduinoJson/src/ArduinoJson/Polyfills/isInteger.hpp b/lib/ArduinoJson/src/ArduinoJson/Polyfills/isInteger.hpp deleted file mode 100644 index 8049079a..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/Polyfills/isInteger.hpp +++ /dev/null @@ -1,19 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#include "./ctype.hpp" - -namespace ArduinoJson { -namespace Internals { - -inline bool isInteger(const char* s) { - if (!s || !*s) return false; - if (issign(*s)) s++; - while (isdigit(*s)) s++; - return *s == '\0'; -} -} // namespace Internals -} // namespace ArduinoJson diff --git a/lib/ArduinoJson/src/ArduinoJson/Polyfills/math.hpp b/lib/ArduinoJson/src/ArduinoJson/Polyfills/math.hpp deleted file mode 100644 index 48773edd..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/Polyfills/math.hpp +++ /dev/null @@ -1,19 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -namespace ArduinoJson { -namespace Internals { -template -bool isNaN(T x) { - return x != x; -} - -template -bool isInfinity(T x) { - return x != 0.0 && x * 2 == x; -} -} -} diff --git a/lib/ArduinoJson/src/ArduinoJson/Polyfills/parseFloat.hpp b/lib/ArduinoJson/src/ArduinoJson/Polyfills/parseFloat.hpp deleted file mode 100644 index 49b0f6fc..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/Polyfills/parseFloat.hpp +++ /dev/null @@ -1,90 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#include "../TypeTraits/FloatTraits.hpp" -#include "./ctype.hpp" -#include "./math.hpp" - -namespace ArduinoJson { -namespace Internals { - -template -inline T parseFloat(const char* s) { - typedef FloatTraits traits; - typedef typename traits::mantissa_type mantissa_t; - typedef typename traits::exponent_type exponent_t; - - if (!s) return 0; // NULL - - bool negative_result = false; - switch (*s) { - case '-': - negative_result = true; - s++; - break; - case '+': - s++; - break; - } - - if (*s == 't') return 1; // true - if (*s == 'n' || *s == 'N') return traits::nan(); - if (*s == 'i' || *s == 'I') - return negative_result ? -traits::inf() : traits::inf(); - - mantissa_t mantissa = 0; - exponent_t exponent_offset = 0; - - while (isdigit(*s)) { - if (mantissa < traits::mantissa_max / 10) - mantissa = mantissa * 10 + (*s - '0'); - else - exponent_offset++; - s++; - } - - if (*s == '.') { - s++; - while (isdigit(*s)) { - if (mantissa < traits::mantissa_max / 10) { - mantissa = mantissa * 10 + (*s - '0'); - exponent_offset--; - } - s++; - } - } - - int exponent = 0; - if (*s == 'e' || *s == 'E') { - s++; - bool negative_exponent = false; - if (*s == '-') { - negative_exponent = true; - s++; - } else if (*s == '+') { - s++; - } - - while (isdigit(*s)) { - exponent = exponent * 10 + (*s - '0'); - if (exponent + exponent_offset > traits::exponent_max) { - if (negative_exponent) - return negative_result ? -0.0f : 0.0f; - else - return negative_result ? -traits::inf() : traits::inf(); - } - s++; - } - if (negative_exponent) exponent = -exponent; - } - exponent += exponent_offset; - - T result = traits::make_float(static_cast(mantissa), exponent); - - return negative_result ? -result : result; -} -} -} diff --git a/lib/ArduinoJson/src/ArduinoJson/Polyfills/parseInteger.hpp b/lib/ArduinoJson/src/ArduinoJson/Polyfills/parseInteger.hpp deleted file mode 100644 index e8f19749..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/Polyfills/parseInteger.hpp +++ /dev/null @@ -1,41 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#include - -#include "../Configuration.hpp" -#include "./ctype.hpp" - -namespace ArduinoJson { -namespace Internals { -template -T parseInteger(const char *s) { - if (!s) return 0; // NULL - - if (*s == 't') return 1; // "true" - - T result = 0; - bool negative_result = false; - - switch (*s) { - case '-': - negative_result = true; - s++; - break; - case '+': - s++; - break; - } - - while (isdigit(*s)) { - result = T(result * 10 + T(*s - '0')); - s++; - } - - return negative_result ? T(~result + 1) : result; -} -} -} diff --git a/lib/ArduinoJson/src/ArduinoJson/RawJson.hpp b/lib/ArduinoJson/src/ArduinoJson/RawJson.hpp deleted file mode 100644 index 4beb980e..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/RawJson.hpp +++ /dev/null @@ -1,46 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -namespace ArduinoJson { - -namespace Internals { -// A special type of data that can be used to insert pregenerated JSON portions. -template -class RawJsonString { - public: - explicit RawJsonString(T str) : _str(str) {} - operator T() const { - return _str; - } - - private: - T _str; -}; - -template -struct StringTraits, void> { - static bool is_null(RawJsonString source) { - return StringTraits::is_null(static_cast(source)); - } - - typedef RawJsonString duplicate_t; - - template - static duplicate_t duplicate(RawJsonString source, Buffer* buffer) { - return duplicate_t(StringTraits::duplicate(source, buffer)); - } - - static const bool has_append = false; - static const bool has_equals = false; - static const bool should_duplicate = StringTraits::should_duplicate; -}; -} - -template -inline Internals::RawJsonString RawJson(T str) { - return Internals::RawJsonString(str); -} -} diff --git a/lib/ArduinoJson/src/ArduinoJson/Serialization/DummyPrint.hpp b/lib/ArduinoJson/src/ArduinoJson/Serialization/DummyPrint.hpp deleted file mode 100644 index 9fdf2d6a..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/Serialization/DummyPrint.hpp +++ /dev/null @@ -1,22 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -namespace ArduinoJson { -namespace Internals { - -// A dummy Print implementation used in JsonPrintable::measureLength() -class DummyPrint { - public: - size_t print(char) { - return 1; - } - - size_t print(const char* s) { - return strlen(s); - } -}; -} -} diff --git a/lib/ArduinoJson/src/ArduinoJson/Serialization/DynamicStringBuilder.hpp b/lib/ArduinoJson/src/ArduinoJson/Serialization/DynamicStringBuilder.hpp deleted file mode 100644 index 41be6392..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/Serialization/DynamicStringBuilder.hpp +++ /dev/null @@ -1,35 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#include "../StringTraits/StringTraits.hpp" - -namespace ArduinoJson { -namespace Internals { - -// A Print implementation that allows to write in a String -template -class DynamicStringBuilder { - public: - DynamicStringBuilder(TString &str) : _str(str) {} - - size_t print(char c) { - StringTraits::append(_str, c); - return 1; - } - - size_t print(const char *s) { - size_t initialLen = _str.length(); - StringTraits::append(_str, s); - return _str.length() - initialLen; - } - - private: - DynamicStringBuilder &operator=(const DynamicStringBuilder &); - - TString &_str; -}; -} -} diff --git a/lib/ArduinoJson/src/ArduinoJson/Serialization/FloatParts.hpp b/lib/ArduinoJson/src/ArduinoJson/Serialization/FloatParts.hpp deleted file mode 100644 index c14e3b55..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/Serialization/FloatParts.hpp +++ /dev/null @@ -1,89 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#include "../Configuration.hpp" -#include "../Polyfills/math.hpp" -#include "../TypeTraits/FloatTraits.hpp" - -namespace ArduinoJson { -namespace Internals { - -template -struct FloatParts { - uint32_t integral; - uint32_t decimal; - int16_t exponent; - int8_t decimalPlaces; - - FloatParts(TFloat value) { - uint32_t maxDecimalPart = sizeof(TFloat) >= 8 ? 1000000000 : 1000000; - decimalPlaces = sizeof(TFloat) >= 8 ? 9 : 6; - - exponent = normalize(value); - - integral = uint32_t(value); - // reduce number of decimal places by the number of integral places - for (uint32_t tmp = integral; tmp >= 10; tmp /= 10) { - maxDecimalPart /= 10; - decimalPlaces--; - } - - TFloat remainder = (value - TFloat(integral)) * TFloat(maxDecimalPart); - - decimal = uint32_t(remainder); - remainder = remainder - TFloat(decimal); - - // rounding: - // increment by 1 if remainder >= 0.5 - decimal += uint32_t(remainder * 2); - if (decimal >= maxDecimalPart) { - decimal = 0; - integral++; - if (exponent && integral >= 10) { - exponent++; - integral = 1; - } - } - - // remove trailing zeros - while (decimal % 10 == 0 && decimalPlaces > 0) { - decimal /= 10; - decimalPlaces--; - } - } - - static int16_t normalize(TFloat& value) { - typedef FloatTraits traits; - int16_t powersOf10 = 0; - - int8_t index = sizeof(TFloat) == 8 ? 8 : 5; - int bit = 1 << index; - - if (value >= ARDUINOJSON_POSITIVE_EXPONENTIATION_THRESHOLD) { - for (; index >= 0; index--) { - if (value >= traits::positiveBinaryPowerOfTen(index)) { - value *= traits::negativeBinaryPowerOfTen(index); - powersOf10 = int16_t(powersOf10 + bit); - } - bit >>= 1; - } - } - - if (value > 0 && value <= ARDUINOJSON_NEGATIVE_EXPONENTIATION_THRESHOLD) { - for (; index >= 0; index--) { - if (value < traits::negativeBinaryPowerOfTenPlusOne(index)) { - value *= traits::positiveBinaryPowerOfTen(index); - powersOf10 = int16_t(powersOf10 - bit); - } - bit >>= 1; - } - } - - return powersOf10; - } -}; -} -} diff --git a/lib/ArduinoJson/src/ArduinoJson/Serialization/IndentedPrint.hpp b/lib/ArduinoJson/src/ArduinoJson/Serialization/IndentedPrint.hpp deleted file mode 100644 index 864f9aaa..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/Serialization/IndentedPrint.hpp +++ /dev/null @@ -1,68 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -namespace ArduinoJson { -namespace Internals { - -// Decorator on top of Print to allow indented output. -// This class is used by JsonPrintable::prettyPrintTo() but can also be used -// for your own purpose, like logging. -template -class IndentedPrint { - public: - explicit IndentedPrint(Print &p) : sink(&p) { - level = 0; - tabSize = 2; - isNewLine = true; - } - - size_t print(char c) { - size_t n = 0; - if (isNewLine) n += writeTabs(); - n += sink->print(c); - isNewLine = c == '\n'; - return n; - } - - size_t print(const char *s) { - // TODO: optimize - size_t n = 0; - while (*s) n += print(*s++); - return n; - } - - // Adds one level of indentation - void indent() { - if (level < MAX_LEVEL) level++; - } - - // Removes one level of indentation - void unindent() { - if (level > 0) level--; - } - - // Set the number of space printed for each level of indentation - void setTabSize(uint8_t n) { - if (n < MAX_TAB_SIZE) tabSize = n & MAX_TAB_SIZE; - } - - private: - Print *sink; - uint8_t level : 4; - uint8_t tabSize : 3; - bool isNewLine : 1; - - size_t writeTabs() { - size_t n = 0; - for (int i = 0; i < level * tabSize; i++) n += sink->print(' '); - return n; - } - - static const int MAX_LEVEL = 15; // because it's only 4 bits - static const int MAX_TAB_SIZE = 7; // because it's only 3 bits -}; -} -} diff --git a/lib/ArduinoJson/src/ArduinoJson/Serialization/JsonPrintable.hpp b/lib/ArduinoJson/src/ArduinoJson/Serialization/JsonPrintable.hpp deleted file mode 100644 index 43d413a8..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/Serialization/JsonPrintable.hpp +++ /dev/null @@ -1,117 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#include "../Configuration.hpp" -#include "../TypeTraits/EnableIf.hpp" -#include "DummyPrint.hpp" -#include "DynamicStringBuilder.hpp" -#include "IndentedPrint.hpp" -#include "JsonSerializer.hpp" -#include "JsonWriter.hpp" -#include "Prettyfier.hpp" -#include "StaticStringBuilder.hpp" - -#if ARDUINOJSON_ENABLE_STD_STREAM -#include "StreamPrintAdapter.hpp" -#endif - -namespace ArduinoJson { -namespace Internals { - -// Implements all the overloads of printTo() and prettyPrintTo() -// Caution: this class use a template parameter to avoid virtual methods. -// This is a bit curious but allows to reduce the size of JsonVariant, JsonArray -// and JsonObject. -template -class JsonPrintable { - public: - template - typename EnableIf::has_append, size_t>::type printTo( - Print &print) const { - JsonWriter writer(print); - JsonSerializer >::serialize(downcast(), writer); - return writer.bytesWritten(); - } - -#if ARDUINOJSON_ENABLE_STD_STREAM - std::ostream &printTo(std::ostream &os) const { - StreamPrintAdapter adapter(os); - printTo(adapter); - return os; - } -#endif - - size_t printTo(char *buffer, size_t bufferSize) const { - StaticStringBuilder sb(buffer, bufferSize); - return printTo(sb); - } - - template - size_t printTo(char (&buffer)[N]) const { - return printTo(buffer, N); - } - - template - typename EnableIf::has_append, size_t>::type printTo( - TString &str) const { - DynamicStringBuilder sb(str); - return printTo(sb); - } - - template - size_t prettyPrintTo(IndentedPrint &print) const { - Prettyfier p(print); - return printTo(p); - } - - size_t prettyPrintTo(char *buffer, size_t bufferSize) const { - StaticStringBuilder sb(buffer, bufferSize); - return prettyPrintTo(sb); - } - - template - size_t prettyPrintTo(char (&buffer)[N]) const { - return prettyPrintTo(buffer, N); - } - - template - typename EnableIf::has_append, size_t>::type - prettyPrintTo(Print &print) const { - IndentedPrint indentedPrint(print); - return prettyPrintTo(indentedPrint); - } - - template - typename EnableIf::has_append, size_t>::type - prettyPrintTo(TString &str) const { - DynamicStringBuilder sb(str); - return prettyPrintTo(sb); - } - - size_t measureLength() const { - DummyPrint dp; - return printTo(dp); - } - - size_t measurePrettyLength() const { - DummyPrint dp; - return prettyPrintTo(dp); - } - - private: - const T &downcast() const { - return *static_cast(this); - } -}; - -#if ARDUINOJSON_ENABLE_STD_STREAM -template -inline std::ostream &operator<<(std::ostream &os, const JsonPrintable &v) { - return v.printTo(os); -} -#endif -} -} diff --git a/lib/ArduinoJson/src/ArduinoJson/Serialization/JsonSerializer.hpp b/lib/ArduinoJson/src/ArduinoJson/Serialization/JsonSerializer.hpp deleted file mode 100644 index 0cb537f7..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/Serialization/JsonSerializer.hpp +++ /dev/null @@ -1,32 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#include "JsonWriter.hpp" - -namespace ArduinoJson { - -class JsonArray; -class JsonObject; -class JsonVariant; - -namespace Internals { - -class JsonArraySubscript; -template -class JsonObjectSubscript; - -template -class JsonSerializer { - public: - static void serialize(const JsonArray &, Writer &); - static void serialize(const JsonArraySubscript &, Writer &); - static void serialize(const JsonObject &, Writer &); - template - static void serialize(const JsonObjectSubscript &, Writer &); - static void serialize(const JsonVariant &, Writer &); -}; -} -} diff --git a/lib/ArduinoJson/src/ArduinoJson/Serialization/JsonSerializerImpl.hpp b/lib/ArduinoJson/src/ArduinoJson/Serialization/JsonSerializerImpl.hpp deleted file mode 100644 index 0faae276..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/Serialization/JsonSerializerImpl.hpp +++ /dev/null @@ -1,103 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#include "../JsonArray.hpp" -#include "../JsonArraySubscript.hpp" -#include "../JsonObject.hpp" -#include "../JsonObjectSubscript.hpp" -#include "../JsonVariant.hpp" -#include "JsonSerializer.hpp" - -template -inline void ArduinoJson::Internals::JsonSerializer::serialize( - const JsonArray& array, Writer& writer) { - writer.beginArray(); - - JsonArray::const_iterator it = array.begin(); - while (it != array.end()) { - serialize(*it, writer); - - ++it; - if (it == array.end()) break; - - writer.writeComma(); - } - - writer.endArray(); -} - -template -inline void ArduinoJson::Internals::JsonSerializer::serialize( - const JsonArraySubscript& arraySubscript, Writer& writer) { - serialize(arraySubscript.as(), writer); -} - -template -inline void ArduinoJson::Internals::JsonSerializer::serialize( - const JsonObject& object, Writer& writer) { - writer.beginObject(); - - JsonObject::const_iterator it = object.begin(); - while (it != object.end()) { - writer.writeString(it->key); - writer.writeColon(); - serialize(it->value, writer); - - ++it; - if (it == object.end()) break; - - writer.writeComma(); - } - - writer.endObject(); -} - -template -template -inline void ArduinoJson::Internals::JsonSerializer::serialize( - const JsonObjectSubscript& objectSubscript, Writer& writer) { - serialize(objectSubscript.template as(), writer); -} - -template -inline void ArduinoJson::Internals::JsonSerializer::serialize( - const JsonVariant& variant, Writer& writer) { - switch (variant._type) { - case JSON_FLOAT: - writer.writeFloat(variant._content.asFloat); - return; - - case JSON_ARRAY: - serialize(*variant._content.asArray, writer); - return; - - case JSON_OBJECT: - serialize(*variant._content.asObject, writer); - return; - - case JSON_STRING: - writer.writeString(variant._content.asString); - return; - - case JSON_UNPARSED: - writer.writeRaw(variant._content.asString); - return; - - case JSON_NEGATIVE_INTEGER: - writer.writeRaw('-'); // Falls through. - - case JSON_POSITIVE_INTEGER: - writer.writeInteger(variant._content.asInteger); - return; - - case JSON_BOOLEAN: - writer.writeBoolean(variant._content.asInteger != 0); - return; - - default: // JSON_UNDEFINED - return; - } -} diff --git a/lib/ArduinoJson/src/ArduinoJson/Serialization/JsonWriter.hpp b/lib/ArduinoJson/src/ArduinoJson/Serialization/JsonWriter.hpp deleted file mode 100644 index 146d51dc..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/Serialization/JsonWriter.hpp +++ /dev/null @@ -1,155 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#include -#include "../Data/Encoding.hpp" -#include "../Data/JsonInteger.hpp" -#include "../Polyfills/attributes.hpp" -#include "../Serialization/FloatParts.hpp" - -namespace ArduinoJson { -namespace Internals { - -// Writes the JSON tokens to a Print implementation -// This class is used by: -// - JsonArray::writeTo() -// - JsonObject::writeTo() -// - JsonVariant::writeTo() -// Its derived by PrettyJsonWriter that overrides some members to add -// indentation. -template -class JsonWriter { - public: - explicit JsonWriter(Print &sink) : _sink(sink), _length(0) {} - - // Returns the number of bytes sent to the Print implementation. - // This is very handy for implementations of printTo() that must return the - // number of bytes written. - size_t bytesWritten() const { - return _length; - } - - void beginArray() { - writeRaw('['); - } - void endArray() { - writeRaw(']'); - } - - void beginObject() { - writeRaw('{'); - } - void endObject() { - writeRaw('}'); - } - - void writeColon() { - writeRaw(':'); - } - void writeComma() { - writeRaw(','); - } - - void writeBoolean(bool value) { - writeRaw(value ? "true" : "false"); - } - - void writeString(const char *value) { - if (!value) { - writeRaw("null"); - } else { - writeRaw('\"'); - while (*value) writeChar(*value++); - writeRaw('\"'); - } - } - - void writeChar(char c) { - char specialChar = Encoding::escapeChar(c); - if (specialChar) { - writeRaw('\\'); - writeRaw(specialChar); - } else { - writeRaw(c); - } - } - - template - void writeFloat(TFloat value) { - if (isNaN(value)) return writeRaw("NaN"); - - if (value < 0.0) { - writeRaw('-'); - value = -value; - } - - if (isInfinity(value)) return writeRaw("Infinity"); - - FloatParts parts(value); - - writeInteger(parts.integral); - if (parts.decimalPlaces) writeDecimals(parts.decimal, parts.decimalPlaces); - - if (parts.exponent < 0) { - writeRaw("e-"); - writeInteger(-parts.exponent); - } - - if (parts.exponent > 0) { - writeRaw('e'); - writeInteger(parts.exponent); - } - } - - template - void writeInteger(UInt value) { - char buffer[22]; - char *end = buffer + sizeof(buffer) - 1; - char *ptr = end; - - *ptr = 0; - do { - *--ptr = char(value % 10 + '0'); - value = UInt(value / 10); - } while (value); - - writeRaw(ptr); - } - - void writeDecimals(uint32_t value, int8_t width) { - // buffer should be big enough for all digits, the dot and the null - // terminator - char buffer[16]; - char *ptr = buffer + sizeof(buffer) - 1; - - // write the string in reverse order - *ptr = 0; - while (width--) { - *--ptr = char(value % 10 + '0'); - value /= 10; - } - *--ptr = '.'; - - // and dump it in the right order - writeRaw(ptr); - } - - void writeRaw(const char *s) { - _length += _sink.print(s); - } - void writeRaw(char c) { - _length += _sink.print(c); - } - - protected: - Print &_sink; - size_t _length; - - private: - JsonWriter &operator=(const JsonWriter &); // cannot be assigned -}; -} -} diff --git a/lib/ArduinoJson/src/ArduinoJson/Serialization/Prettyfier.hpp b/lib/ArduinoJson/src/ArduinoJson/Serialization/Prettyfier.hpp deleted file mode 100644 index 8b4f0d2e..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/Serialization/Prettyfier.hpp +++ /dev/null @@ -1,133 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#include "IndentedPrint.hpp" - -namespace ArduinoJson { -namespace Internals { - -// Converts a compact JSON string into an indented one. -template -class Prettyfier { - public: - explicit Prettyfier(IndentedPrint& p) : _sink(p) { - _previousChar = 0; - _inString = false; - } - - size_t print(char c) { - size_t n = _inString ? handleStringChar(c) : handleMarkupChar(c); - _previousChar = c; - return n; - } - - size_t print(const char* s) { - // TODO: optimize - size_t n = 0; - while (*s) n += print(*s++); - return n; - } - - private: - Prettyfier& operator=(const Prettyfier&); // cannot be assigned - - bool inEmptyBlock() { - return _previousChar == '{' || _previousChar == '['; - } - - size_t handleStringChar(char c) { - bool isQuote = c == '"' && _previousChar != '\\'; - - if (isQuote) _inString = false; - - return _sink.print(c); - } - - size_t handleMarkupChar(char c) { - switch (c) { - case '{': - case '[': - return writeBlockOpen(c); - - case '}': - case ']': - return writeBlockClose(c); - - case ':': - return writeColon(); - - case ',': - return writeComma(); - - case '"': - return writeQuoteOpen(); - - default: - return writeNormalChar(c); - } - } - - size_t writeBlockClose(char c) { - size_t n = 0; - n += unindentIfNeeded(); - n += _sink.print(c); - return n; - } - - size_t writeBlockOpen(char c) { - size_t n = 0; - n += indentIfNeeded(); - n += _sink.print(c); - return n; - } - - size_t writeColon() { - size_t n = 0; - n += _sink.print(": "); - return n; - } - - size_t writeComma() { - size_t n = 0; - n += _sink.print(",\r\n"); - return n; - } - - size_t writeQuoteOpen() { - _inString = true; - size_t n = 0; - n += indentIfNeeded(); - n += _sink.print('"'); - return n; - } - - size_t writeNormalChar(char c) { - size_t n = 0; - n += indentIfNeeded(); - n += _sink.print(c); - return n; - } - - size_t indentIfNeeded() { - if (!inEmptyBlock()) return 0; - - _sink.indent(); - return _sink.print("\r\n"); - } - - size_t unindentIfNeeded() { - if (inEmptyBlock()) return 0; - - _sink.unindent(); - return _sink.print("\r\n"); - } - - char _previousChar; - IndentedPrint& _sink; - bool _inString; -}; -} -} diff --git a/lib/ArduinoJson/src/ArduinoJson/Serialization/StaticStringBuilder.hpp b/lib/ArduinoJson/src/ArduinoJson/Serialization/StaticStringBuilder.hpp deleted file mode 100644 index 9617bbd9..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/Serialization/StaticStringBuilder.hpp +++ /dev/null @@ -1,36 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -namespace ArduinoJson { -namespace Internals { - -// A Print implementation that allows to write in a char[] -class StaticStringBuilder { - public: - StaticStringBuilder(char *buf, size_t size) : end(buf + size - 1), p(buf) { - *p = '\0'; - } - - size_t print(char c) { - if (p >= end) return 0; - *p++ = c; - *p = '\0'; - return 1; - } - - size_t print(const char *s) { - char *begin = p; - while (p < end && *s) *p++ = *s++; - *p = '\0'; - return size_t(p - begin); - } - - private: - char *end; - char *p; -}; -} -} diff --git a/lib/ArduinoJson/src/ArduinoJson/Serialization/StreamPrintAdapter.hpp b/lib/ArduinoJson/src/ArduinoJson/Serialization/StreamPrintAdapter.hpp deleted file mode 100644 index 60f0af4a..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/Serialization/StreamPrintAdapter.hpp +++ /dev/null @@ -1,39 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#include "../Configuration.hpp" - -#if ARDUINOJSON_ENABLE_STD_STREAM - -#include - -namespace ArduinoJson { -namespace Internals { - -class StreamPrintAdapter { - public: - explicit StreamPrintAdapter(std::ostream& os) : _os(os) {} - - size_t print(char c) { - _os << c; - return 1; - } - - size_t print(const char* s) { - _os << s; - return strlen(s); - } - - private: - // cannot be assigned - StreamPrintAdapter& operator=(const StreamPrintAdapter&); - - std::ostream& _os; -}; -} -} - -#endif // ARDUINOJSON_ENABLE_STD_STREAM diff --git a/lib/ArduinoJson/src/ArduinoJson/StaticJsonBuffer.hpp b/lib/ArduinoJson/src/ArduinoJson/StaticJsonBuffer.hpp deleted file mode 100644 index 267d9d01..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/StaticJsonBuffer.hpp +++ /dev/null @@ -1,126 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#include "JsonBufferBase.hpp" - -namespace ArduinoJson { -namespace Internals { - -class StaticJsonBufferBase : public JsonBufferBase { - public: - class String { - public: - String(StaticJsonBufferBase* parent) : _parent(parent) { - _start = parent->_buffer + parent->_size; - } - - void append(char c) { - if (_parent->canAlloc(1)) { - char* last = static_cast(_parent->doAlloc(1)); - *last = c; - } - } - - const char* c_str() const { - if (_parent->canAlloc(1)) { - char* last = static_cast(_parent->doAlloc(1)); - *last = '\0'; - return _start; - } else { - return NULL; - } - } - - private: - StaticJsonBufferBase* _parent; - char* _start; - }; - - StaticJsonBufferBase(char* buffer, size_t capa) - : _buffer(buffer), _capacity(capa), _size(0) {} - - // Gets the capacity of the buffer in bytes - size_t capacity() const { - return _capacity; - } - - // Gets the current usage of the buffer in bytes - size_t size() const { - return _size; - } - - // Allocates the specified amount of bytes in the buffer - virtual void* alloc(size_t bytes) { - alignNextAlloc(); - if (!canAlloc(bytes)) return NULL; - return doAlloc(bytes); - } - - // Resets the buffer. - // USE WITH CAUTION: this invalidates all previously allocated data - void clear() { - _size = 0; - } - - String startString() { - return String(this); - } - - protected: - ~StaticJsonBufferBase() {} - - private: - void alignNextAlloc() { - _size = round_size_up(_size); - } - - bool canAlloc(size_t bytes) const { - return _size + bytes <= _capacity; - } - - void* doAlloc(size_t bytes) { - void* p = &_buffer[_size]; - _size += bytes; - return p; - } - - char* _buffer; - size_t _capacity; - size_t _size; -}; -} - -#if defined(__clang__) -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wnon-virtual-dtor" -#elif defined(__GNUC__) -#if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6) -#pragma GCC diagnostic push -#endif -#pragma GCC diagnostic ignored "-Wnon-virtual-dtor" -#endif - -// Implements a JsonBuffer with fixed memory allocation. -// The template paramenter CAPACITY specifies the capacity of the buffer in -// bytes. -template -class StaticJsonBuffer : public Internals::StaticJsonBufferBase { - public: - explicit StaticJsonBuffer() - : Internals::StaticJsonBufferBase(_buffer, CAPACITY) {} - - private: - char _buffer[CAPACITY]; -}; -} - -#if defined(__clang__) -#pragma clang diagnostic pop -#elif defined(__GNUC__) -#if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6) -#pragma GCC diagnostic pop -#endif -#endif diff --git a/lib/ArduinoJson/src/ArduinoJson/StringTraits/ArduinoStream.hpp b/lib/ArduinoJson/src/ArduinoJson/StringTraits/ArduinoStream.hpp deleted file mode 100644 index 5db0852b..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/StringTraits/ArduinoStream.hpp +++ /dev/null @@ -1,61 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#if ARDUINOJSON_ENABLE_ARDUINO_STREAM - -#include - -namespace ArduinoJson { -namespace Internals { - -struct ArduinoStreamTraits { - class Reader { - Stream& _stream; - char _current, _next; - - public: - Reader(Stream& stream) : _stream(stream), _current(0), _next(0) {} - - void move() { - _current = _next; - _next = 0; - } - - char current() { - if (!_current) _current = read(); - return _current; - } - - char next() { - // assumes that current() has been called - if (!_next) _next = read(); - return _next; - } - - private: - char read() { - // don't use _stream.read() as it ignores the timeout - char c = 0; - _stream.readBytes(&c, 1); - return c; - } - }; - - static const bool has_append = false; - static const bool has_equals = false; -}; - -template -struct StringTraits< - TStream, - // match any type that is derived from Stream: - typename EnableIf< - IsBaseOf::type>::value>::type> - : ArduinoStreamTraits {}; -} -} - -#endif diff --git a/lib/ArduinoJson/src/ArduinoJson/StringTraits/CharPointer.hpp b/lib/ArduinoJson/src/ArduinoJson/StringTraits/CharPointer.hpp deleted file mode 100644 index 98896ccf..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/StringTraits/CharPointer.hpp +++ /dev/null @@ -1,64 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -namespace ArduinoJson { -namespace Internals { - -template -struct CharPointerTraits { - class Reader { - const TChar* _ptr; - - public: - Reader(const TChar* ptr) - : _ptr(ptr ? ptr : reinterpret_cast("")) {} - - void move() { - ++_ptr; - } - - char current() const { - return char(_ptr[0]); - } - - char next() const { - return char(_ptr[1]); - } - }; - - static bool equals(const TChar* str, const char* expected) { - const char* actual = reinterpret_cast(str); - if (!actual || !expected) return actual == expected; - return strcmp(actual, expected) == 0; - } - - static bool is_null(const TChar* str) { - return !str; - } - - typedef const char* duplicate_t; - - template - static duplicate_t duplicate(const TChar* str, Buffer* buffer) { - if (!str) return NULL; - size_t size = strlen(reinterpret_cast(str)) + 1; - void* dup = buffer->alloc(size); - if (dup != NULL) memcpy(dup, str, size); - return static_cast(dup); - } - - static const bool has_append = false; - static const bool has_equals = true; - static const bool should_duplicate = !IsConst::value; -}; - -// char*, unsigned char*, signed char* -// const char*, const unsigned char*, const signed char* -template -struct StringTraits::value>::type> - : CharPointerTraits {}; -} // namespace Internals -} // namespace ArduinoJson diff --git a/lib/ArduinoJson/src/ArduinoJson/StringTraits/FlashString.hpp b/lib/ArduinoJson/src/ArduinoJson/StringTraits/FlashString.hpp deleted file mode 100644 index 0701b9ba..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/StringTraits/FlashString.hpp +++ /dev/null @@ -1,61 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#if ARDUINOJSON_ENABLE_PROGMEM - -namespace ArduinoJson { -namespace Internals { -template <> -struct StringTraits { - class Reader { - const char* _ptr; - - public: - Reader(const __FlashStringHelper* ptr) - : _ptr(reinterpret_cast(ptr)) {} - - void move() { - _ptr++; - } - - char current() const { - return pgm_read_byte_near(_ptr); - } - - char next() const { - return pgm_read_byte_near(_ptr + 1); - } - }; - - static bool equals(const __FlashStringHelper* str, const char* expected) { - const char* actual = reinterpret_cast(str); - if (!actual || !expected) return actual == expected; - return strcmp_P(expected, actual) == 0; - } - - static bool is_null(const __FlashStringHelper* str) { - return !str; - } - - typedef const char* duplicate_t; - - template - static duplicate_t duplicate(const __FlashStringHelper* str, Buffer* buffer) { - if (!str) return NULL; - size_t size = strlen_P((const char*)str) + 1; - void* dup = buffer->alloc(size); - if (dup != NULL) memcpy_P(dup, (const char*)str, size); - return static_cast(dup); - } - - static const bool has_append = false; - static const bool has_equals = true; - static const bool should_duplicate = true; -}; -} // namespace Internals -} // namespace ArduinoJson - -#endif diff --git a/lib/ArduinoJson/src/ArduinoJson/StringTraits/StdStream.hpp b/lib/ArduinoJson/src/ArduinoJson/StringTraits/StdStream.hpp deleted file mode 100644 index 227c7440..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/StringTraits/StdStream.hpp +++ /dev/null @@ -1,60 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#if ARDUINOJSON_ENABLE_STD_STREAM - -#include - -namespace ArduinoJson { -namespace Internals { - -struct StdStreamTraits { - class Reader { - std::istream& _stream; - char _current, _next; - - public: - Reader(std::istream& stream) : _stream(stream), _current(0), _next(0) {} - - void move() { - _current = _next; - _next = 0; - } - - char current() { - if (!_current) _current = read(); - return _current; - } - - char next() { - // assumes that current() has been called - if (!_next) _next = read(); - return _next; - } - - private: - Reader& operator=(const Reader&); // Visual Studio C4512 - - char read() { - return _stream.eof() ? '\0' : static_cast(_stream.get()); - } - }; - - static const bool has_append = false; - static const bool has_equals = false; -}; - -template -struct StringTraits< - TStream, - // match any type that is derived from std::istream: - typename EnableIf::type>::value>::type> - : StdStreamTraits {}; -} -} - -#endif diff --git a/lib/ArduinoJson/src/ArduinoJson/StringTraits/StdString.hpp b/lib/ArduinoJson/src/ArduinoJson/StringTraits/StdString.hpp deleted file mode 100644 index 35f4461d..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/StringTraits/StdString.hpp +++ /dev/null @@ -1,77 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#if ARDUINOJSON_ENABLE_STD_STRING || ARDUINOJSON_ENABLE_ARDUINO_STRING - -#if ARDUINOJSON_ENABLE_ARDUINO_STRING -#include -#endif - -#if ARDUINOJSON_ENABLE_STD_STRING -#include -#endif - -namespace ArduinoJson { -namespace Internals { - -template -struct StdStringTraits { - typedef const char* duplicate_t; - - template - static duplicate_t duplicate(const TString& str, Buffer* buffer) { - if (!str.c_str()) return NULL; // <- Arduino string can return NULL - size_t size = str.length() + 1; - void* dup = buffer->alloc(size); - if (dup != NULL) memcpy(dup, str.c_str(), size); - return static_cast(dup); - } - - static bool is_null(const TString& str) { - // Arduino's String::c_str() can return NULL - return !str.c_str(); - } - - struct Reader : CharPointerTraits::Reader { - Reader(const TString& str) : CharPointerTraits::Reader(str.c_str()) {} - }; - - static bool equals(const TString& str, const char* expected) { - // Arduino's String::c_str() can return NULL - const char* actual = str.c_str(); - if (!actual || !expected) return actual == expected; - return 0 == strcmp(actual, expected); - } - - static void append(TString& str, char c) { - str += c; - } - - static void append(TString& str, const char* s) { - str += s; - } - - static const bool has_append = true; - static const bool has_equals = true; - static const bool should_duplicate = true; -}; - -#if ARDUINOJSON_ENABLE_ARDUINO_STRING -template <> -struct StringTraits : StdStringTraits {}; -template <> -struct StringTraits : StdStringTraits { -}; -#endif - -#if ARDUINOJSON_ENABLE_STD_STRING -template <> -struct StringTraits : StdStringTraits {}; -#endif -} // namespace Internals -} // namespace ArduinoJson - -#endif diff --git a/lib/ArduinoJson/src/ArduinoJson/StringTraits/StringTraits.hpp b/lib/ArduinoJson/src/ArduinoJson/StringTraits/StringTraits.hpp deleted file mode 100644 index dd5694b2..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/StringTraits/StringTraits.hpp +++ /dev/null @@ -1,36 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#include -#include "../Configuration.hpp" -#include "../TypeTraits/EnableIf.hpp" -#include "../TypeTraits/IsBaseOf.hpp" -#include "../TypeTraits/IsChar.hpp" -#include "../TypeTraits/IsConst.hpp" -#include "../TypeTraits/RemoveReference.hpp" - -namespace ArduinoJson { -namespace Internals { - -template -struct StringTraits { - static const bool has_append = false; - static const bool has_equals = false; -}; - -template -struct StringTraits : StringTraits {}; - -template -struct StringTraits : StringTraits {}; -} -} - -#include "ArduinoStream.hpp" -#include "CharPointer.hpp" -#include "FlashString.hpp" -#include "StdStream.hpp" -#include "StdString.hpp" diff --git a/lib/ArduinoJson/src/ArduinoJson/TypeTraits/EnableIf.hpp b/lib/ArduinoJson/src/ArduinoJson/TypeTraits/EnableIf.hpp deleted file mode 100644 index 83fc5e07..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/TypeTraits/EnableIf.hpp +++ /dev/null @@ -1,19 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -namespace ArduinoJson { -namespace Internals { - -// A meta-function that return the type T if Condition is true. -template -struct EnableIf {}; - -template -struct EnableIf { - typedef T type; -}; -} -} diff --git a/lib/ArduinoJson/src/ArduinoJson/TypeTraits/FloatTraits.hpp b/lib/ArduinoJson/src/ArduinoJson/TypeTraits/FloatTraits.hpp deleted file mode 100644 index 648cc82f..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/TypeTraits/FloatTraits.hpp +++ /dev/null @@ -1,171 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#include -#include // for size_t -#include "../Configuration.hpp" -#include "../Polyfills/math.hpp" - -namespace ArduinoJson { -namespace Internals { - -template -struct FloatTraits {}; - -template -struct FloatTraits { - typedef int64_t mantissa_type; - static const short mantissa_bits = 52; - static const mantissa_type mantissa_max = - (static_cast(1) << mantissa_bits) - 1; - - typedef int16_t exponent_type; - static const exponent_type exponent_max = 308; - - template - static T make_float(T m, TExponent e) { - if (e > 0) { - for (uint8_t index = 0; e != 0; index++) { - if (e & 1) m *= positiveBinaryPowerOfTen(index); - e >>= 1; - } - } else { - e = TExponent(-e); - for (uint8_t index = 0; e != 0; index++) { - if (e & 1) m *= negativeBinaryPowerOfTen(index); - e >>= 1; - } - } - return m; - } - - static T positiveBinaryPowerOfTen(int index) { - static T factors[] = { - 1e1, - 1e2, - 1e4, - 1e8, - 1e16, - forge(0x4693B8B5, 0xB5056E17), // 1e32 - forge(0x4D384F03, 0xE93FF9F5), // 1e64 - forge(0x5A827748, 0xF9301D32), // 1e128 - forge(0x75154FDD, 0x7F73BF3C) // 1e256 - }; - return factors[index]; - } - - static T negativeBinaryPowerOfTen(int index) { - static T factors[] = { - forge(0x3FB99999, 0x9999999A), // 1e-1 - forge(0x3F847AE1, 0x47AE147B), // 1e-2 - forge(0x3F1A36E2, 0xEB1C432D), // 1e-4 - forge(0x3E45798E, 0xE2308C3A), // 1e-8 - forge(0x3C9CD2B2, 0x97D889BC), // 1e-16 - forge(0x3949F623, 0xD5A8A733), // 1e-32 - forge(0x32A50FFD, 0x44F4A73D), // 1e-64 - forge(0x255BBA08, 0xCF8C979D), // 1e-128 - forge(0x0AC80628, 0x64AC6F43) // 1e-256 - }; - return factors[index]; - } - - static T negativeBinaryPowerOfTenPlusOne(int index) { - static T factors[] = { - 1e0, - forge(0x3FB99999, 0x9999999A), // 1e-1 - forge(0x3F50624D, 0xD2F1A9FC), // 1e-3 - forge(0x3E7AD7F2, 0x9ABCAF48), // 1e-7 - forge(0x3CD203AF, 0x9EE75616), // 1e-15 - forge(0x398039D6, 0x65896880), // 1e-31 - forge(0x32DA53FC, 0x9631D10D), // 1e-63 - forge(0x25915445, 0x81B7DEC2), // 1e-127 - forge(0x0AFE07B2, 0x7DD78B14) // 1e-255 - }; - return factors[index]; - } - - static T nan() { - return forge(0x7ff80000, 0x00000000); - } - - static T inf() { - return forge(0x7ff00000, 0x00000000); - } - - // constructs a double floating point values from its binary representation - // we use this function to workaround platforms with single precision literals - // (for example, when -fsingle-precision-constant is passed to GCC) - static T forge(uint32_t msb, uint32_t lsb) { - union { - uint64_t integerBits; - T floatBits; - }; - integerBits = (uint64_t(msb) << 32) | lsb; - return floatBits; - } -}; - -template -struct FloatTraits { - typedef int32_t mantissa_type; - static const short mantissa_bits = 23; - static const mantissa_type mantissa_max = - (static_cast(1) << mantissa_bits) - 1; - - typedef int8_t exponent_type; - static const exponent_type exponent_max = 38; - - template - static T make_float(T m, TExponent e) { - if (e > 0) { - for (uint8_t index = 0; e != 0; index++) { - if (e & 1) m *= positiveBinaryPowerOfTen(index); - e >>= 1; - } - } else { - e = -e; - for (uint8_t index = 0; e != 0; index++) { - if (e & 1) m *= negativeBinaryPowerOfTen(index); - e >>= 1; - } - } - return m; - } - - static T positiveBinaryPowerOfTen(int index) { - static T factors[] = {1e1f, 1e2f, 1e4f, 1e8f, 1e16f, 1e32f}; - return factors[index]; - } - - static T negativeBinaryPowerOfTen(int index) { - static T factors[] = {1e-1f, 1e-2f, 1e-4f, 1e-8f, 1e-16f, 1e-32f}; - return factors[index]; - } - - static T negativeBinaryPowerOfTenPlusOne(int index) { - static T factors[] = {1e0f, 1e-1f, 1e-3f, 1e-7f, 1e-15f, 1e-31f}; - return factors[index]; - } - - static T forge(uint32_t bits) { - union { - uint32_t integerBits; - T floatBits; - }; - integerBits = bits; - return floatBits; - } - - static T nan() { - return forge(0x7fc00000); - } - - static T inf() { - return forge(0x7f800000); - } -}; -} -} diff --git a/lib/ArduinoJson/src/ArduinoJson/TypeTraits/IsArray.hpp b/lib/ArduinoJson/src/ArduinoJson/TypeTraits/IsArray.hpp deleted file mode 100644 index 25992311..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/TypeTraits/IsArray.hpp +++ /dev/null @@ -1,24 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -namespace ArduinoJson { -namespace Internals { - -// A meta-function that return the type T without the const modifier -template -struct IsArray { - static const bool value = false; -}; -template -struct IsArray { - static const bool value = true; -}; -template -struct IsArray { - static const bool value = true; -}; -} -} diff --git a/lib/ArduinoJson/src/ArduinoJson/TypeTraits/IsBaseOf.hpp b/lib/ArduinoJson/src/ArduinoJson/TypeTraits/IsBaseOf.hpp deleted file mode 100644 index bf24e965..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/TypeTraits/IsBaseOf.hpp +++ /dev/null @@ -1,27 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -namespace ArduinoJson { -namespace Internals { - -// A meta-function that returns true if Derived inherits from TBase is an -// integral type. -template -class IsBaseOf { - protected: // <- to avoid GCC's "all member functions in class are private" - typedef char Yes[1]; - typedef char No[2]; - - static Yes &probe(const TBase *); - static No &probe(...); - - public: - enum { - value = sizeof(probe(reinterpret_cast(0))) == sizeof(Yes) - }; -}; -} -} diff --git a/lib/ArduinoJson/src/ArduinoJson/TypeTraits/IsChar.hpp b/lib/ArduinoJson/src/ArduinoJson/TypeTraits/IsChar.hpp deleted file mode 100644 index d97cec21..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/TypeTraits/IsChar.hpp +++ /dev/null @@ -1,23 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#include "IsSame.hpp" - -namespace ArduinoJson { -namespace Internals { - -// A meta-function that returns true if T is a charater -template -struct IsChar { - static const bool value = IsSame::value || - IsSame::value || - IsSame::value; -}; - -template -struct IsChar : IsChar {}; -} -} diff --git a/lib/ArduinoJson/src/ArduinoJson/TypeTraits/IsConst.hpp b/lib/ArduinoJson/src/ArduinoJson/TypeTraits/IsConst.hpp deleted file mode 100644 index 512ee5ca..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/TypeTraits/IsConst.hpp +++ /dev/null @@ -1,21 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -namespace ArduinoJson { -namespace Internals { - -// A meta-function that return the type T without the const modifier -template -struct IsConst { - static const bool value = false; -}; - -template -struct IsConst { - static const bool value = true; -}; -} -} diff --git a/lib/ArduinoJson/src/ArduinoJson/TypeTraits/IsFloatingPoint.hpp b/lib/ArduinoJson/src/ArduinoJson/TypeTraits/IsFloatingPoint.hpp deleted file mode 100644 index e41a6824..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/TypeTraits/IsFloatingPoint.hpp +++ /dev/null @@ -1,18 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#include "IsSame.hpp" - -namespace ArduinoJson { -namespace Internals { - -// A meta-function that returns true if T is a floating point type -template -struct IsFloatingPoint { - static const bool value = IsSame::value || IsSame::value; -}; -} -} diff --git a/lib/ArduinoJson/src/ArduinoJson/TypeTraits/IsIntegral.hpp b/lib/ArduinoJson/src/ArduinoJson/TypeTraits/IsIntegral.hpp deleted file mode 100644 index 17ae5f28..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/TypeTraits/IsIntegral.hpp +++ /dev/null @@ -1,26 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#include "IsSame.hpp" -#include "IsSignedIntegral.hpp" -#include "IsUnsignedIntegral.hpp" - -namespace ArduinoJson { -namespace Internals { - -// A meta-function that returns true if T is an integral type. -template -struct IsIntegral { - static const bool value = IsSignedIntegral::value || - IsUnsignedIntegral::value || - IsSame::value; - // CAUTION: differs from std::is_integral as it doesn't include bool -}; - -template -struct IsIntegral : IsIntegral {}; -} -} diff --git a/lib/ArduinoJson/src/ArduinoJson/TypeTraits/IsSame.hpp b/lib/ArduinoJson/src/ArduinoJson/TypeTraits/IsSame.hpp deleted file mode 100644 index 06567c93..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/TypeTraits/IsSame.hpp +++ /dev/null @@ -1,21 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -namespace ArduinoJson { -namespace Internals { - -// A meta-function that returns true if types T and U are the same. -template -struct IsSame { - static const bool value = false; -}; - -template -struct IsSame { - static const bool value = true; -}; -} -} diff --git a/lib/ArduinoJson/src/ArduinoJson/TypeTraits/IsSignedIntegral.hpp b/lib/ArduinoJson/src/ArduinoJson/TypeTraits/IsSignedIntegral.hpp deleted file mode 100644 index 7334eb9c..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/TypeTraits/IsSignedIntegral.hpp +++ /dev/null @@ -1,28 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#include "../Configuration.hpp" -#include "IsSame.hpp" - -namespace ArduinoJson { -namespace Internals { - -// A meta-function that returns true if T is an integral type. -template -struct IsSignedIntegral { - static const bool value = - IsSame::value || IsSame::value || - IsSame::value || IsSame::value || -#if ARDUINOJSON_USE_LONG_LONG - IsSame::value || -#endif -#if ARDUINOJSON_USE_INT64 - IsSame::value || -#endif - false; -}; -} -} diff --git a/lib/ArduinoJson/src/ArduinoJson/TypeTraits/IsUnsignedIntegral.hpp b/lib/ArduinoJson/src/ArduinoJson/TypeTraits/IsUnsignedIntegral.hpp deleted file mode 100644 index 938423f5..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/TypeTraits/IsUnsignedIntegral.hpp +++ /dev/null @@ -1,28 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#include "../Configuration.hpp" -#include "IsSame.hpp" - -namespace ArduinoJson { -namespace Internals { - -// A meta-function that returns true if T is an integral type. -template -struct IsUnsignedIntegral { - static const bool value = - IsSame::value || IsSame::value || - IsSame::value || IsSame::value || -#if ARDUINOJSON_USE_LONG_LONG - IsSame::value || -#endif -#if ARDUINOJSON_USE_INT64 - IsSame::value || -#endif - false; -}; -} -} diff --git a/lib/ArduinoJson/src/ArduinoJson/TypeTraits/IsVariant.hpp b/lib/ArduinoJson/src/ArduinoJson/TypeTraits/IsVariant.hpp deleted file mode 100644 index f8b299f7..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/TypeTraits/IsVariant.hpp +++ /dev/null @@ -1,17 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#include "IsBaseOf.hpp" - -namespace ArduinoJson { -namespace Internals { - -class JsonVariantTag {}; - -template -struct IsVariant : IsBaseOf {}; -} -} diff --git a/lib/ArduinoJson/src/ArduinoJson/TypeTraits/RemoveConst.hpp b/lib/ArduinoJson/src/ArduinoJson/TypeTraits/RemoveConst.hpp deleted file mode 100644 index 39d4cb5a..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/TypeTraits/RemoveConst.hpp +++ /dev/null @@ -1,20 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -namespace ArduinoJson { -namespace Internals { - -// A meta-function that return the type T without the const modifier -template -struct RemoveConst { - typedef T type; -}; -template -struct RemoveConst { - typedef T type; -}; -} -} diff --git a/lib/ArduinoJson/src/ArduinoJson/TypeTraits/RemoveReference.hpp b/lib/ArduinoJson/src/ArduinoJson/TypeTraits/RemoveReference.hpp deleted file mode 100644 index 395a1288..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/TypeTraits/RemoveReference.hpp +++ /dev/null @@ -1,20 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -namespace ArduinoJson { -namespace Internals { - -// A meta-function that return the type T without the reference modifier. -template -struct RemoveReference { - typedef T type; -}; -template -struct RemoveReference { - typedef T type; -}; -} -} diff --git a/lib/ArduinoJson/src/ArduinoJson/version.hpp b/lib/ArduinoJson/src/ArduinoJson/version.hpp deleted file mode 100644 index e5fa1e2e..00000000 --- a/lib/ArduinoJson/src/ArduinoJson/version.hpp +++ /dev/null @@ -1,10 +0,0 @@ -// ArduinoJson - arduinojson.org -// Copyright Benoit Blanchon 2014-2018 -// MIT License - -#pragma once - -#define ARDUINOJSON_VERSION "5.13.3" -#define ARDUINOJSON_VERSION_MAJOR 5 -#define ARDUINOJSON_VERSION_MINOR 13 -#define ARDUINOJSON_VERSION_REVISION 3 diff --git a/lib/DHT-sensor-library/.github/ISSUE_TEMPLATE.md b/lib/DHT-sensor-library/.github/ISSUE_TEMPLATE.md deleted file mode 100644 index f0e26146..00000000 --- a/lib/DHT-sensor-library/.github/ISSUE_TEMPLATE.md +++ /dev/null @@ -1,46 +0,0 @@ -Thank you for opening an issue on an Adafruit Arduino library repository. To -improve the speed of resolution please review the following guidelines and -common troubleshooting steps below before creating the issue: - -- **Do not use GitHub issues for troubleshooting projects and issues.** Instead use - the forums at http://forums.adafruit.com to ask questions and troubleshoot why - something isn't working as expected. In many cases the problem is a common issue - that you will more quickly receive help from the forum community. GitHub issues - are meant for known defects in the code. If you don't know if there is a defect - in the code then start with troubleshooting on the forum first. - -- **If following a tutorial or guide be sure you didn't miss a step.** Carefully - check all of the steps and commands to run have been followed. Consult the - forum if you're unsure or have questions about steps in a guide/tutorial. - -- **For Arduino projects check these very common issues to ensure they don't apply**: - - - For uploading sketches or communicating with the board make sure you're using - a **USB data cable** and **not** a **USB charge-only cable**. It is sometimes - very hard to tell the difference between a data and charge cable! Try using the - cable with other devices or swapping to another cable to confirm it is not - the problem. - - - **Be sure you are supplying adequate power to the board.** Check the specs of - your board and plug in an external power supply. In many cases just - plugging a board into your computer is not enough to power it and other - peripherals. - - - **Double check all soldering joints and connections.** Flakey connections - cause many mysterious problems. See the [guide to excellent soldering](https://learn.adafruit.com/adafruit-guide-excellent-soldering/tools) for examples of good solder joints. - - - **Ensure you are using an official Arduino or Adafruit board.** We can't - guarantee a clone board will have the same functionality and work as expected - with this code and don't support them. - -If you're sure this issue is a defect in the code and checked the steps above -please fill in the following fields to provide enough troubleshooting information. -You may delete the guideline and text above to just leave the following details: - -- Arduino board: **INSERT ARDUINO BOARD NAME/TYPE HERE** - -- Arduino IDE version (found in Arduino -> About Arduino menu): **INSERT ARDUINO - VERSION HERE** - -- List the steps to reproduce the problem below (if possible attach a sketch or - copy the sketch code in too): **LIST REPRO STEPS BELOW** diff --git a/lib/DHT-sensor-library/.github/PULL_REQUEST_TEMPLATE.md b/lib/DHT-sensor-library/.github/PULL_REQUEST_TEMPLATE.md deleted file mode 100644 index 7b641eb8..00000000 --- a/lib/DHT-sensor-library/.github/PULL_REQUEST_TEMPLATE.md +++ /dev/null @@ -1,26 +0,0 @@ -Thank you for creating a pull request to contribute to Adafruit's GitHub code! -Before you open the request please review the following guidelines and tips to -help it be more easily integrated: - -- **Describe the scope of your change--i.e. what the change does and what parts - of the code were modified.** This will help us understand any risks of integrating - the code. - -- **Describe any known limitations with your change.** For example if the change - doesn't apply to a supported platform of the library please mention it. - -- **Please run any tests or examples that can exercise your modified code.** We - strive to not break users of the code and running tests/examples helps with this - process. - -Thank you again for contributing! We will try to test and integrate the change -as soon as we can, but be aware we have many GitHub repositories to manage and -can't immediately respond to every request. There is no need to bump or check in -on a pull request (it will clutter the discussion of the request). - -Also don't be worried if the request is closed or not integrated--sometimes the -priorities of Adafruit's GitHub code (education, ease of use) might not match the -priorities of the pull request. Don't fret, the open source community thrives on -forks and GitHub makes it easy to keep your changes in a forked repo. - -After reviewing the guidelines above you can delete this text from the pull request. diff --git a/lib/DHT-sensor-library/DHT.cpp b/lib/DHT-sensor-library/DHT.cpp deleted file mode 100644 index 86ad91c4..00000000 --- a/lib/DHT-sensor-library/DHT.cpp +++ /dev/null @@ -1,259 +0,0 @@ -/* DHT library - -MIT license -written by Adafruit Industries -*/ - -#include "DHT.h" - -#define MIN_INTERVAL 2000 - -DHT::DHT(uint8_t pin, uint8_t type, uint8_t count) { - _pin = pin; - _type = type; - #ifdef __AVR - _bit = digitalPinToBitMask(pin); - _port = digitalPinToPort(pin); - #endif - _maxcycles = microsecondsToClockCycles(1000); // 1 millisecond timeout for - // reading pulses from DHT sensor. - // Note that count is now ignored as the DHT reading algorithm adjusts itself - // basd on the speed of the processor. -} - -void DHT::begin(void) { - // set up the pins! - pinMode(_pin, INPUT_PULLUP); - // Using this value makes sure that millis() - lastreadtime will be - // >= MIN_INTERVAL right away. Note that this assignment wraps around, - // but so will the subtraction. - _lastreadtime = -MIN_INTERVAL; - DEBUG_PRINT("Max clock cycles: "); DEBUG_PRINTLN(_maxcycles, DEC); -} - -//boolean S == Scale. True == Fahrenheit; False == Celcius -float DHT::readTemperature(bool S, bool force) { - float f = NAN; - - if (read(force)) { - switch (_type) { - case DHT11: - f = data[2]; - if(S) { - f = convertCtoF(f); - } - break; - case DHT22: - case DHT21: - f = data[2] & 0x7F; - f *= 256; - f += data[3]; - f *= 0.1; - if (data[2] & 0x80) { - f *= -1; - } - if(S) { - f = convertCtoF(f); - } - break; - } - } - return f; -} - -float DHT::convertCtoF(float c) { - return c * 1.8 + 32; -} - -float DHT::convertFtoC(float f) { - return (f - 32) * 0.55555; -} - -float DHT::readHumidity(bool force) { - float f = NAN; - if (read()) { - switch (_type) { - case DHT11: - f = data[0]; - break; - case DHT22: - case DHT21: - f = data[0]; - f *= 256; - f += data[1]; - f *= 0.1; - break; - } - } - return f; -} - -//boolean isFahrenheit: True == Fahrenheit; False == Celcius -float DHT::computeHeatIndex(float temperature, float percentHumidity, bool isFahrenheit) { - // Using both Rothfusz and Steadman's equations - // http://www.wpc.ncep.noaa.gov/html/heatindex_equation.shtml - float hi; - - if (!isFahrenheit) - temperature = convertCtoF(temperature); - - hi = 0.5 * (temperature + 61.0 + ((temperature - 68.0) * 1.2) + (percentHumidity * 0.094)); - - if (hi > 79) { - hi = -42.379 + - 2.04901523 * temperature + - 10.14333127 * percentHumidity + - -0.22475541 * temperature*percentHumidity + - -0.00683783 * pow(temperature, 2) + - -0.05481717 * pow(percentHumidity, 2) + - 0.00122874 * pow(temperature, 2) * percentHumidity + - 0.00085282 * temperature*pow(percentHumidity, 2) + - -0.00000199 * pow(temperature, 2) * pow(percentHumidity, 2); - - if((percentHumidity < 13) && (temperature >= 80.0) && (temperature <= 112.0)) - hi -= ((13.0 - percentHumidity) * 0.25) * sqrt((17.0 - abs(temperature - 95.0)) * 0.05882); - - else if((percentHumidity > 85.0) && (temperature >= 80.0) && (temperature <= 87.0)) - hi += ((percentHumidity - 85.0) * 0.1) * ((87.0 - temperature) * 0.2); - } - - return isFahrenheit ? hi : convertFtoC(hi); -} - -boolean DHT::read(bool force) { - // Check if sensor was read less than two seconds ago and return early - // to use last reading. - uint32_t currenttime = millis(); - if (!force && ((currenttime - _lastreadtime) < 2000)) { - return _lastresult; // return last correct measurement - } - _lastreadtime = currenttime; - - // Reset 40 bits of received data to zero. - data[0] = data[1] = data[2] = data[3] = data[4] = 0; - - // Send start signal. See DHT datasheet for full signal diagram: - // http://www.adafruit.com/datasheets/Digital%20humidity%20and%20temperature%20sensor%20AM2302.pdf - - // Go into high impedence state to let pull-up raise data line level and - // start the reading process. - digitalWrite(_pin, HIGH); - delay(250); - - // First set data line low for 20 milliseconds. - pinMode(_pin, OUTPUT); - digitalWrite(_pin, LOW); - delay(20); - - uint32_t cycles[80]; - { - // Turn off interrupts temporarily because the next sections are timing critical - // and we don't want any interruptions. - InterruptLock lock; - - // End the start signal by setting data line high for 40 microseconds. - digitalWrite(_pin, HIGH); - delayMicroseconds(40); - - // Now start reading the data line to get the value from the DHT sensor. - pinMode(_pin, INPUT_PULLUP); - delayMicroseconds(10); // Delay a bit to let sensor pull data line low. - - // First expect a low signal for ~80 microseconds followed by a high signal - // for ~80 microseconds again. - if (expectPulse(LOW) == 0) { - DEBUG_PRINTLN(F("Timeout waiting for start signal low pulse.")); - _lastresult = false; - return _lastresult; - } - if (expectPulse(HIGH) == 0) { - DEBUG_PRINTLN(F("Timeout waiting for start signal high pulse.")); - _lastresult = false; - return _lastresult; - } - - // Now read the 40 bits sent by the sensor. Each bit is sent as a 50 - // microsecond low pulse followed by a variable length high pulse. If the - // high pulse is ~28 microseconds then it's a 0 and if it's ~70 microseconds - // then it's a 1. We measure the cycle count of the initial 50us low pulse - // and use that to compare to the cycle count of the high pulse to determine - // if the bit is a 0 (high state cycle count < low state cycle count), or a - // 1 (high state cycle count > low state cycle count). Note that for speed all - // the pulses are read into a array and then examined in a later step. - for (int i=0; i<80; i+=2) { - cycles[i] = expectPulse(LOW); - cycles[i+1] = expectPulse(HIGH); - } - } // Timing critical code is now complete. - - // Inspect pulses and determine which ones are 0 (high state cycle count < low - // state cycle count), or 1 (high state cycle count > low state cycle count). - for (int i=0; i<40; ++i) { - uint32_t lowCycles = cycles[2*i]; - uint32_t highCycles = cycles[2*i+1]; - if ((lowCycles == 0) || (highCycles == 0)) { - DEBUG_PRINTLN(F("Timeout waiting for pulse.")); - _lastresult = false; - return _lastresult; - } - data[i/8] <<= 1; - // Now compare the low and high cycle times to see if the bit is a 0 or 1. - if (highCycles > lowCycles) { - // High cycles are greater than 50us low cycle count, must be a 1. - data[i/8] |= 1; - } - // Else high cycles are less than (or equal to, a weird case) the 50us low - // cycle count so this must be a zero. Nothing needs to be changed in the - // stored data. - } - - DEBUG_PRINTLN(F("Received:")); - DEBUG_PRINT(data[0], HEX); DEBUG_PRINT(F(", ")); - DEBUG_PRINT(data[1], HEX); DEBUG_PRINT(F(", ")); - DEBUG_PRINT(data[2], HEX); DEBUG_PRINT(F(", ")); - DEBUG_PRINT(data[3], HEX); DEBUG_PRINT(F(", ")); - DEBUG_PRINT(data[4], HEX); DEBUG_PRINT(F(" =? ")); - DEBUG_PRINTLN((data[0] + data[1] + data[2] + data[3]) & 0xFF, HEX); - - // Check we read 40 bits and that the checksum matches. - if (data[4] == ((data[0] + data[1] + data[2] + data[3]) & 0xFF)) { - _lastresult = true; - return _lastresult; - } - else { - DEBUG_PRINTLN(F("Checksum failure!")); - _lastresult = false; - return _lastresult; - } -} - -// Expect the signal line to be at the specified level for a period of time and -// return a count of loop cycles spent at that level (this cycle count can be -// used to compare the relative time of two pulses). If more than a millisecond -// ellapses without the level changing then the call fails with a 0 response. -// This is adapted from Arduino's pulseInLong function (which is only available -// in the very latest IDE versions): -// https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/wiring_pulse.c -uint32_t DHT::expectPulse(bool level) { - uint32_t count = 0; - // On AVR platforms use direct GPIO port access as it's much faster and better - // for catching pulses that are 10's of microseconds in length: - #ifdef __AVR - uint8_t portState = level ? _bit : 0; - while ((*portInputRegister(_port) & _bit) == portState) { - if (count++ >= _maxcycles) { - return 0; // Exceeded timeout, fail. - } - } - // Otherwise fall back to using digitalRead (this seems to be necessary on ESP8266 - // right now, perhaps bugs in direct port access functions?). - #else - while (digitalRead(_pin) == level) { - if (count++ >= _maxcycles) { - return 0; // Exceeded timeout, fail. - } - } - #endif - - return count; -} diff --git a/lib/DHT-sensor-library/DHT.h b/lib/DHT-sensor-library/DHT.h deleted file mode 100644 index d81f6dbc..00000000 --- a/lib/DHT-sensor-library/DHT.h +++ /dev/null @@ -1,75 +0,0 @@ -/* DHT library - -MIT license -written by Adafruit Industries -*/ -#ifndef DHT_H -#define DHT_H - -#if ARDUINO >= 100 - #include "Arduino.h" -#else - #include "WProgram.h" -#endif - - -// Uncomment to enable printing out nice debug messages. -//#define DHT_DEBUG - -// Define where debug output will be printed. -#define DEBUG_PRINTER Serial - -// Setup debug printing macros. -#ifdef DHT_DEBUG - #define DEBUG_PRINT(...) { DEBUG_PRINTER.print(__VA_ARGS__); } - #define DEBUG_PRINTLN(...) { DEBUG_PRINTER.println(__VA_ARGS__); } -#else - #define DEBUG_PRINT(...) {} - #define DEBUG_PRINTLN(...) {} -#endif - -// Define types of sensors. -#define DHT11 11 -#define DHT22 22 -#define DHT21 21 -#define AM2301 21 - - -class DHT { - public: - DHT(uint8_t pin, uint8_t type, uint8_t count=6); - void begin(void); - float readTemperature(bool S=false, bool force=false); - float convertCtoF(float); - float convertFtoC(float); - float computeHeatIndex(float temperature, float percentHumidity, bool isFahrenheit=true); - float readHumidity(bool force=false); - boolean read(bool force=false); - - private: - uint8_t data[5]; - uint8_t _pin, _type; - #ifdef __AVR - // Use direct GPIO access on an 8-bit AVR so keep track of the port and bitmask - // for the digital pin connected to the DHT. Other platforms will use digitalRead. - uint8_t _bit, _port; - #endif - uint32_t _lastreadtime, _maxcycles; - bool _lastresult; - - uint32_t expectPulse(bool level); - -}; - -class InterruptLock { - public: - InterruptLock() { - noInterrupts(); - } - ~InterruptLock() { - interrupts(); - } - -}; - -#endif diff --git a/lib/DHT-sensor-library/DHT_U.cpp b/lib/DHT-sensor-library/DHT_U.cpp deleted file mode 100644 index efc7963c..00000000 --- a/lib/DHT-sensor-library/DHT_U.cpp +++ /dev/null @@ -1,179 +0,0 @@ -// DHT Temperature & Humidity Unified Sensor Library -// Copyright (c) 2014 Adafruit Industries -// Author: Tony DiCola - -// 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. -#include "DHT_U.h" - -DHT_Unified::DHT_Unified(uint8_t pin, uint8_t type, uint8_t count, int32_t tempSensorId, int32_t humiditySensorId): - _dht(pin, type, count), - _type(type), - _temp(this, tempSensorId), - _humidity(this, humiditySensorId) -{} - -void DHT_Unified::begin() { - _dht.begin(); -} - -void DHT_Unified::setName(sensor_t* sensor) { - switch(_type) { - case DHT11: - strncpy(sensor->name, "DHT11", sizeof(sensor->name) - 1); - break; - case DHT21: - strncpy(sensor->name, "DHT21", sizeof(sensor->name) - 1); - break; - case DHT22: - strncpy(sensor->name, "DHT22", sizeof(sensor->name) - 1); - break; - default: - // TODO: Perhaps this should be an error? However main DHT library doesn't enforce - // restrictions on the sensor type value. Pick a generic name for now. - strncpy(sensor->name, "DHT?", sizeof(sensor->name) - 1); - break; - } - sensor->name[sizeof(sensor->name)- 1] = 0; -} - -void DHT_Unified::setMinDelay(sensor_t* sensor) { - switch(_type) { - case DHT11: - sensor->min_delay = 1000000L; // 1 second (in microseconds) - break; - case DHT21: - sensor->min_delay = 2000000L; // 2 seconds (in microseconds) - break; - case DHT22: - sensor->min_delay = 2000000L; // 2 seconds (in microseconds) - break; - default: - // Default to slowest sample rate in case of unknown type. - sensor->min_delay = 2000000L; // 2 seconds (in microseconds) - break; - } -} - -DHT_Unified::Temperature::Temperature(DHT_Unified* parent, int32_t id): - _parent(parent), - _id(id) -{} - -bool DHT_Unified::Temperature::getEvent(sensors_event_t* event) { - // Clear event definition. - memset(event, 0, sizeof(sensors_event_t)); - // Populate sensor reading values. - event->version = sizeof(sensors_event_t); - event->sensor_id = _id; - event->type = SENSOR_TYPE_AMBIENT_TEMPERATURE; - event->timestamp = millis(); - event->temperature = _parent->_dht.readTemperature(); - - return true; -} - -void DHT_Unified::Temperature::getSensor(sensor_t* sensor) { - // Clear sensor definition. - memset(sensor, 0, sizeof(sensor_t)); - // Set sensor name. - _parent->setName(sensor); - // Set version and ID - sensor->version = DHT_SENSOR_VERSION; - sensor->sensor_id = _id; - // Set type and characteristics. - sensor->type = SENSOR_TYPE_AMBIENT_TEMPERATURE; - _parent->setMinDelay(sensor); - switch (_parent->_type) { - case DHT11: - sensor->max_value = 50.0F; - sensor->min_value = 0.0F; - sensor->resolution = 2.0F; - break; - case DHT21: - sensor->max_value = 80.0F; - sensor->min_value = -40.0F; - sensor->resolution = 0.1F; - break; - case DHT22: - sensor->max_value = 125.0F; - sensor->min_value = -40.0F; - sensor->resolution = 0.1F; - break; - default: - // Unknown type, default to 0. - sensor->max_value = 0.0F; - sensor->min_value = 0.0F; - sensor->resolution = 0.0F; - break; - } -} - -DHT_Unified::Humidity::Humidity(DHT_Unified* parent, int32_t id): - _parent(parent), - _id(id) -{} - -bool DHT_Unified::Humidity::getEvent(sensors_event_t* event) { - // Clear event definition. - memset(event, 0, sizeof(sensors_event_t)); - // Populate sensor reading values. - event->version = sizeof(sensors_event_t); - event->sensor_id = _id; - event->type = SENSOR_TYPE_RELATIVE_HUMIDITY; - event->timestamp = millis(); - event->relative_humidity = _parent->_dht.readHumidity(); - - return true; -} - -void DHT_Unified::Humidity::getSensor(sensor_t* sensor) { - // Clear sensor definition. - memset(sensor, 0, sizeof(sensor_t)); - // Set sensor name. - _parent->setName(sensor); - // Set version and ID - sensor->version = DHT_SENSOR_VERSION; - sensor->sensor_id = _id; - // Set type and characteristics. - sensor->type = SENSOR_TYPE_RELATIVE_HUMIDITY; - _parent->setMinDelay(sensor); - switch (_parent->_type) { - case DHT11: - sensor->max_value = 80.0F; - sensor->min_value = 20.0F; - sensor->resolution = 5.0F; - break; - case DHT21: - sensor->max_value = 100.0F; - sensor->min_value = 0.0F; - sensor->resolution = 0.1F; - break; - case DHT22: - sensor->max_value = 100.0F; - sensor->min_value = 0.0F; - sensor->resolution = 0.1F; - break; - default: - // Unknown type, default to 0. - sensor->max_value = 0.0F; - sensor->min_value = 0.0F; - sensor->resolution = 0.0F; - break; - } -} diff --git a/lib/DHT-sensor-library/DHT_U.h b/lib/DHT-sensor-library/DHT_U.h deleted file mode 100644 index d9ee709c..00000000 --- a/lib/DHT-sensor-library/DHT_U.h +++ /dev/null @@ -1,78 +0,0 @@ -// DHT Temperature & Humidity Unified Sensor Library -// Copyright (c) 2014 Adafruit Industries -// Author: Tony DiCola - -// 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. -#ifndef DHT_U_H -#define DHT_U_H - -#include -#include - -#define DHT_SENSOR_VERSION 1 - -class DHT_Unified { -public: - DHT_Unified(uint8_t pin, uint8_t type, uint8_t count=6, int32_t tempSensorId=-1, int32_t humiditySensorId=-1); - void begin(); - - class Temperature : public Adafruit_Sensor { - public: - Temperature(DHT_Unified* parent, int32_t id); - bool getEvent(sensors_event_t* event); - void getSensor(sensor_t* sensor); - - private: - DHT_Unified* _parent; - int32_t _id; - - }; - - class Humidity : public Adafruit_Sensor { - public: - Humidity(DHT_Unified* parent, int32_t id); - bool getEvent(sensors_event_t* event); - void getSensor(sensor_t* sensor); - - private: - DHT_Unified* _parent; - int32_t _id; - - }; - - Temperature temperature() { - return _temp; - } - - Humidity humidity() { - return _humidity; - } - -private: - DHT _dht; - uint8_t _type; - Temperature _temp; - Humidity _humidity; - - void setName(sensor_t* sensor); - void setMinDelay(sensor_t* sensor); - -}; - -#endif diff --git a/lib/DHT-sensor-library/README.md b/lib/DHT-sensor-library/README.md deleted file mode 100644 index d32afdc6..00000000 --- a/lib/DHT-sensor-library/README.md +++ /dev/null @@ -1,15 +0,0 @@ -This is an Arduino library for the DHT series of low cost temperature/humidity sensors. - -Tutorial: https://learn.adafruit.com/dht - -To download. click the DOWNLOADS button in the top right corner, rename the uncompressed folder DHT. Check that the DHT folder contains DHT.cpp and DHT.h. Place the DHT library folder your /libraries/ folder. You may need to create the libraries subfolder if its your first library. Restart the IDE. - -# Adafruit DHT Humidity & Temperature Unified Sensor Library - -This library also includes an optional class for the -[DHT humidity and temperature sensor](https://learn.adafruit.com/dht/overview) -which is designed to work with the [Adafruit unified sensor library](https://learn.adafruit.com/using-the-adafruit-unified-sensor-driver/introduction). - -You must have the following Arduino libraries installed to use this class: - -- [Adafruit Unified Sensor Library](https://github.com/adafruit/Adafruit_Sensor) diff --git a/lib/DHT-sensor-library/examples/DHT_Unified_Sensor/DHT_Unified_Sensor.ino b/lib/DHT-sensor-library/examples/DHT_Unified_Sensor/DHT_Unified_Sensor.ino deleted file mode 100644 index 4820f2e8..00000000 --- a/lib/DHT-sensor-library/examples/DHT_Unified_Sensor/DHT_Unified_Sensor.ino +++ /dev/null @@ -1,84 +0,0 @@ -// DHT Temperature & Humidity Sensor -// Unified Sensor Library Example -// Written by Tony DiCola for Adafruit Industries -// Released under an MIT license. - -// Depends on the following Arduino libraries: -// - Adafruit Unified Sensor Library: https://github.com/adafruit/Adafruit_Sensor -// - DHT Sensor Library: https://github.com/adafruit/DHT-sensor-library - -#include -#include -#include - -#define DHTPIN 2 // Pin which is connected to the DHT sensor. - -// Uncomment the type of sensor in use: -//#define DHTTYPE DHT11 // DHT 11 -#define DHTTYPE DHT22 // DHT 22 (AM2302) -//#define DHTTYPE DHT21 // DHT 21 (AM2301) - -// See guide for details on sensor wiring and usage: -// https://learn.adafruit.com/dht/overview - -DHT_Unified dht(DHTPIN, DHTTYPE); - -uint32_t delayMS; - -void setup() { - Serial.begin(9600); - // Initialize device. - dht.begin(); - Serial.println("DHTxx Unified Sensor Example"); - // Print temperature sensor details. - sensor_t sensor; - dht.temperature().getSensor(&sensor); - Serial.println("------------------------------------"); - Serial.println("Temperature"); - Serial.print ("Sensor: "); Serial.println(sensor.name); - Serial.print ("Driver Ver: "); Serial.println(sensor.version); - Serial.print ("Unique ID: "); Serial.println(sensor.sensor_id); - Serial.print ("Max Value: "); Serial.print(sensor.max_value); Serial.println(" *C"); - Serial.print ("Min Value: "); Serial.print(sensor.min_value); Serial.println(" *C"); - Serial.print ("Resolution: "); Serial.print(sensor.resolution); Serial.println(" *C"); - Serial.println("------------------------------------"); - // Print humidity sensor details. - dht.humidity().getSensor(&sensor); - Serial.println("------------------------------------"); - Serial.println("Humidity"); - Serial.print ("Sensor: "); Serial.println(sensor.name); - Serial.print ("Driver Ver: "); Serial.println(sensor.version); - Serial.print ("Unique ID: "); Serial.println(sensor.sensor_id); - Serial.print ("Max Value: "); Serial.print(sensor.max_value); Serial.println("%"); - Serial.print ("Min Value: "); Serial.print(sensor.min_value); Serial.println("%"); - Serial.print ("Resolution: "); Serial.print(sensor.resolution); Serial.println("%"); - Serial.println("------------------------------------"); - // Set delay between sensor readings based on sensor details. - delayMS = sensor.min_delay / 1000; -} - -void loop() { - // Delay between measurements. - delay(delayMS); - // Get temperature event and print its value. - sensors_event_t event; - dht.temperature().getEvent(&event); - if (isnan(event.temperature)) { - Serial.println("Error reading temperature!"); - } - else { - Serial.print("Temperature: "); - Serial.print(event.temperature); - Serial.println(" *C"); - } - // Get humidity event and print its value. - dht.humidity().getEvent(&event); - if (isnan(event.relative_humidity)) { - Serial.println("Error reading humidity!"); - } - else { - Serial.print("Humidity: "); - Serial.print(event.relative_humidity); - Serial.println("%"); - } -} diff --git a/lib/DHT-sensor-library/examples/DHTtester/DHTtester.ino b/lib/DHT-sensor-library/examples/DHTtester/DHTtester.ino deleted file mode 100644 index ae6c41a1..00000000 --- a/lib/DHT-sensor-library/examples/DHTtester/DHTtester.ino +++ /dev/null @@ -1,69 +0,0 @@ -// Example testing sketch for various DHT humidity/temperature sensors -// Written by ladyada, public domain - -#include "DHT.h" - -#define DHTPIN 2 // what digital pin we're connected to - -// Uncomment whatever type you're using! -//#define DHTTYPE DHT11 // DHT 11 -#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321 -//#define DHTTYPE DHT21 // DHT 21 (AM2301) - -// Connect pin 1 (on the left) of the sensor to +5V -// NOTE: If using a board with 3.3V logic like an Arduino Due connect pin 1 -// to 3.3V instead of 5V! -// Connect pin 2 of the sensor to whatever your DHTPIN is -// Connect pin 4 (on the right) of the sensor to GROUND -// Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor - -// Initialize DHT sensor. -// Note that older versions of this library took an optional third parameter to -// tweak the timings for faster processors. This parameter is no longer needed -// as the current DHT reading algorithm adjusts itself to work on faster procs. -DHT dht(DHTPIN, DHTTYPE); - -void setup() { - Serial.begin(9600); - Serial.println("DHTxx test!"); - - dht.begin(); -} - -void loop() { - // Wait a few seconds between measurements. - delay(2000); - - // Reading temperature or humidity takes about 250 milliseconds! - // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor) - float h = dht.readHumidity(); - // Read temperature as Celsius (the default) - float t = dht.readTemperature(); - // Read temperature as Fahrenheit (isFahrenheit = true) - float f = dht.readTemperature(true); - - // Check if any reads failed and exit early (to try again). - if (isnan(h) || isnan(t) || isnan(f)) { - Serial.println("Failed to read from DHT sensor!"); - return; - } - - // Compute heat index in Fahrenheit (the default) - float hif = dht.computeHeatIndex(f, h); - // Compute heat index in Celsius (isFahreheit = false) - float hic = dht.computeHeatIndex(t, h, false); - - Serial.print("Humidity: "); - Serial.print(h); - Serial.print(" %\t"); - Serial.print("Temperature: "); - Serial.print(t); - Serial.print(" *C "); - Serial.print(f); - Serial.print(" *F\t"); - Serial.print("Heat index: "); - Serial.print(hic); - Serial.print(" *C "); - Serial.print(hif); - Serial.println(" *F"); -} diff --git a/lib/DHT-sensor-library/keywords.txt b/lib/DHT-sensor-library/keywords.txt deleted file mode 100644 index 146d4fa6..00000000 --- a/lib/DHT-sensor-library/keywords.txt +++ /dev/null @@ -1,22 +0,0 @@ -########################################### -# Syntax Coloring Map For DHT-sensor-library -########################################### - -########################################### -# Datatypes (KEYWORD1) -########################################### - -DHT KEYWORD1 - -########################################### -# Methods and Functions (KEYWORD2) -########################################### - -begin KEYWORD2 -readTemperature KEYWORD2 -convertCtoF KEYWORD2 -convertFtoC KEYWORD2 -computeHeatIndex KEYWORD2 -readHumidity KEYWORD2 -read KEYWORD2 - diff --git a/lib/DHT-sensor-library/library.properties b/lib/DHT-sensor-library/library.properties deleted file mode 100644 index a54c1dc2..00000000 --- a/lib/DHT-sensor-library/library.properties +++ /dev/null @@ -1,9 +0,0 @@ -name=DHT sensor library -version=1.3.0 -author=Adafruit -maintainer=Adafruit -sentence=Arduino library for DHT11, DHT22, etc Temp & Humidity Sensors -paragraph=Arduino library for DHT11, DHT22, etc Temp & Humidity Sensors -category=Sensors -url=https://github.com/adafruit/DHT-sensor-library -architectures=* diff --git a/lib/ESP32_BLE_Arduino/README.md b/lib/ESP32_BLE_Arduino/README.md deleted file mode 100644 index e80fbe0c..00000000 --- a/lib/ESP32_BLE_Arduino/README.md +++ /dev/null @@ -1,15 +0,0 @@ -# ESP32 BLE for Arduino -The Arduino IDE provides an excellent library package manager where versions of libraries can be downloaded and installed. This Github project provides the repository for the ESP32 BLE support for Arduino. - -The actual source of the project which is being maintained can be found here: - -https://github.com/nkolban/esp32-snippets - -Issues and questions should be raised here: - -https://github.com/nkolban/esp32-snippets/issues - - -Documentation for using the library can be found here: - -https://github.com/nkolban/esp32-snippets/tree/master/Documentation \ No newline at end of file diff --git a/lib/ESP32_BLE_Arduino/examples/BLE_client/BLE_client.ino b/lib/ESP32_BLE_Arduino/examples/BLE_client/BLE_client.ino deleted file mode 100644 index c0b6163c..00000000 --- a/lib/ESP32_BLE_Arduino/examples/BLE_client/BLE_client.ino +++ /dev/null @@ -1,134 +0,0 @@ -/** - * A BLE client example that is rich in capabilities. - */ - -#include "BLEDevice.h" -//#include "BLEScan.h" - -// The remote service we wish to connect to. -static BLEUUID serviceUUID("91bad492-b950-4226-aa2b-4ede9fa42f59"); -// The characteristic of the remote service we are interested in. -static BLEUUID charUUID("0d563a58-196a-48ce-ace2-dfec78acc814"); - -static BLEAddress *pServerAddress; -static boolean doConnect = false; -static boolean connected = false; -static BLERemoteCharacteristic* pRemoteCharacteristic; - -static void notifyCallback( - BLERemoteCharacteristic* pBLERemoteCharacteristic, - uint8_t* pData, - size_t length, - bool isNotify) { - Serial.print("Notify callback for characteristic "); - Serial.print(pBLERemoteCharacteristic->getUUID().toString().c_str()); - Serial.print(" of data length "); - Serial.println(length); -} - -bool connectToServer(BLEAddress pAddress) { - Serial.print("Forming a connection to "); - Serial.println(pAddress.toString().c_str()); - - BLEClient* pClient = BLEDevice::createClient(); - Serial.println(" - Created client"); - - // Connect to the remove BLE Server. - pClient->connect(pAddress); - Serial.println(" - Connected to server"); - - // Obtain a reference to the service we are after in the remote BLE server. - BLERemoteService* pRemoteService = pClient->getService(serviceUUID); - if (pRemoteService == nullptr) { - Serial.print("Failed to find our service UUID: "); - Serial.println(serviceUUID.toString().c_str()); - return false; - } - Serial.println(" - Found our service"); - - - // Obtain a reference to the characteristic in the service of the remote BLE server. - pRemoteCharacteristic = pRemoteService->getCharacteristic(charUUID); - if (pRemoteCharacteristic == nullptr) { - Serial.print("Failed to find our characteristic UUID: "); - Serial.println(charUUID.toString().c_str()); - return false; - } - Serial.println(" - Found our characteristic"); - - // Read the value of the characteristic. - std::string value = pRemoteCharacteristic->readValue(); - Serial.print("The characteristic value was: "); - Serial.println(value.c_str()); - - pRemoteCharacteristic->registerForNotify(notifyCallback); -} -/** - * Scan for BLE servers and find the first one that advertises the service we are looking for. - */ -class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks { - /** - * Called for each advertising BLE server. - */ - void onResult(BLEAdvertisedDevice advertisedDevice) { - Serial.print("BLE Advertised Device found: "); - Serial.println(advertisedDevice.toString().c_str()); - - // We have found a device, let us now see if it contains the service we are looking for. - if (advertisedDevice.haveServiceUUID() && advertisedDevice.getServiceUUID().equals(serviceUUID)) { - - // - Serial.print("Found our device! address: "); - advertisedDevice.getScan()->stop(); - - pServerAddress = new BLEAddress(advertisedDevice.getAddress()); - doConnect = true; - - } // Found our server - } // onResult -}; // MyAdvertisedDeviceCallbacks - - -void setup() { - Serial.begin(115200); - Serial.println("Starting Arduino BLE Client application..."); - BLEDevice::init(""); - - // Retrieve a Scanner and set the callback we want to use to be informed when we - // have detected a new device. Specify that we want active scanning and start the - // scan to run for 30 seconds. - BLEScan* pBLEScan = BLEDevice::getScan(); - pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks()); - pBLEScan->setActiveScan(true); - pBLEScan->start(30); -} // End of setup. - - -// This is the Arduino main loop function. -void loop() { - - // If the flag "doConnect" is true then we have scanned for and found the desired - // BLE Server with which we wish to connect. Now we connect to it. Once we are - // connected we set the connected flag to be true. - if (doConnect == true) { - if (connectToServer(*pServerAddress)) { - Serial.println("We are now connected to the BLE Server."); - connected = true; - } else { - Serial.println("We have failed to connect to the server; there is nothin more we will do."); - } - doConnect = false; - } - - // If we are connected to a peer BLE Server, update the characteristic each time we are reached - // with the current time since boot. - if (connected) { - String newValue = "Time since boot: " + String(millis()/1000); - Serial.println("Setting new characteristic value to \"" + newValue + "\""); - - // Set the characteristic's value to be the array of bytes that is actually a string. - pRemoteCharacteristic->writeValue(newValue.c_str(), newValue.length()); - } - - delay(1000); // Delay a second between loops. -} // End of loop diff --git a/lib/ESP32_BLE_Arduino/examples/BLE_iBeacon/BLE_iBeacon.ino b/lib/ESP32_BLE_Arduino/examples/BLE_iBeacon/BLE_iBeacon.ino deleted file mode 100644 index 5f6ed002..00000000 --- a/lib/ESP32_BLE_Arduino/examples/BLE_iBeacon/BLE_iBeacon.ino +++ /dev/null @@ -1,104 +0,0 @@ -/* - Based on Neil Kolban example for IDF: https://github.com/nkolban/esp32-snippets/blob/master/cpp_utils/tests/BLE%20Tests/SampleScan.cpp - Ported to Arduino ESP32 by pcbreflux -*/ - - -/* - Create a BLE server that will send periodic iBeacon frames. - The design of creating the BLE server is: - 1. Create a BLE Server - 2. Create advertising data - 3. Start advertising. - 4. wait - 5. Stop advertising. - 6. deep sleep - -*/ -#include "sys/time.h" - -#include "BLEDevice.h" -#include "BLEServer.h" -#include "BLEUtils.h" -#include "BLEBeacon.h" -#include "esp_sleep.h" - -#define GPIO_DEEP_SLEEP_DURATION 10 // sleep x seconds and then wake up -RTC_DATA_ATTR static time_t last; // remember last boot in RTC Memory -RTC_DATA_ATTR static uint32_t bootcount; // remember number of boots in RTC Memory - -#ifdef __cplusplus -extern "C" { -#endif - -uint8_t temprature_sens_read(); -//uint8_t g_phyFuns; - -#ifdef __cplusplus -} -#endif - -// See the following for generating UUIDs: -// https://www.uuidgenerator.net/ -BLEAdvertising *pAdvertising; -struct timeval now; - -#define BEACON_UUID "8ec76ea3-6668-48da-9866-75be8bc86f4d" // UUID 1 128-Bit (may use linux tool uuidgen or random numbers via https://www.uuidgenerator.net/) - -void setBeacon() { - - BLEBeacon oBeacon = BLEBeacon(); - oBeacon.setManufacturerId(0x4C00); // fake Apple 0x004C LSB (ENDIAN_CHANGE_U16!) - oBeacon.setProximityUUID(BLEUUID(BEACON_UUID)); - oBeacon.setMajor((bootcount & 0xFFFF0000) >> 16); - oBeacon.setMinor(bootcount&0xFFFF); - BLEAdvertisementData oAdvertisementData = BLEAdvertisementData(); - BLEAdvertisementData oScanResponseData = BLEAdvertisementData(); - - oAdvertisementData.setFlags(0x04); // BR_EDR_NOT_SUPPORTED 0x04 - - std::string strServiceData = ""; - - strServiceData += (char)26; // Len - strServiceData += (char)0xFF; // Type - strServiceData += oBeacon.getData(); - oAdvertisementData.addData(strServiceData); - - pAdvertising->setAdvertisementData(oAdvertisementData); - pAdvertising->setScanResponseData(oScanResponseData); - -} - -void setup() { - - - Serial.begin(115200); - gettimeofday(&now, NULL); - - Serial.printf("start ESP32 %d\n",bootcount++); - - Serial.printf("deep sleep (%lds since last reset, %lds since last boot)\n",now.tv_sec,now.tv_sec-last); - - last = now.tv_sec; - - // Create the BLE Device - BLEDevice::init(""); - - // Create the BLE Server - BLEServer *pServer = BLEDevice::createServer(); - - pAdvertising = pServer->getAdvertising(); - - setBeacon(); - // Start advertising - pAdvertising->start(); - Serial.println("Advertizing started..."); - delay(100); - pAdvertising->stop(); - Serial.printf("enter deep sleep\n"); - esp_deep_sleep(1000000LL * GPIO_DEEP_SLEEP_DURATION); - Serial.printf("in deep sleep\n"); -} - -void loop() { -} diff --git a/lib/ESP32_BLE_Arduino/examples/BLE_notify/BLE_notify.ino b/lib/ESP32_BLE_Arduino/examples/BLE_notify/BLE_notify.ino deleted file mode 100644 index 5e915bea..00000000 --- a/lib/ESP32_BLE_Arduino/examples/BLE_notify/BLE_notify.ino +++ /dev/null @@ -1,105 +0,0 @@ -/* - Video: https://www.youtube.com/watch?v=oCMOYS71NIU - Based on Neil Kolban example for IDF: https://github.com/nkolban/esp32-snippets/blob/master/cpp_utils/tests/BLE%20Tests/SampleNotify.cpp - Ported to Arduino ESP32 by Evandro Copercini - - Create a BLE server that, once we receive a connection, will send periodic notifications. - The service advertises itself as: 4fafc201-1fb5-459e-8fcc-c5c9c331914b - And has a characteristic of: beb5483e-36e1-4688-b7f5-ea07361b26a8 - - The design of creating the BLE server is: - 1. Create a BLE Server - 2. Create a BLE Service - 3. Create a BLE Characteristic on the Service - 4. Create a BLE Descriptor on the characteristic - 5. Start the service. - 6. Start advertising. - - A connect hander associated with the server starts a background task that performs notification - every couple of seconds. -*/ -#include -#include -#include -#include - -BLEServer* pServer = NULL; -BLECharacteristic* pCharacteristic = NULL; -bool deviceConnected = false; -bool oldDeviceConnected = false; -uint8_t value = 0; - -// See the following for generating UUIDs: -// https://www.uuidgenerator.net/ - -#define SERVICE_UUID "4fafc201-1fb5-459e-8fcc-c5c9c331914b" -#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8" - - -class MyServerCallbacks: public BLEServerCallbacks { - void onConnect(BLEServer* pServer) { - deviceConnected = true; - }; - - void onDisconnect(BLEServer* pServer) { - deviceConnected = false; - } -}; - - - -void setup() { - Serial.begin(115200); - - // Create the BLE Device - BLEDevice::init("MyESP32"); - - // Create the BLE Server - pServer = BLEDevice::createServer(); - pServer->setCallbacks(new MyServerCallbacks()); - - // Create the BLE Service - BLEService *pService = pServer->createService(SERVICE_UUID); - - // Create a BLE Characteristic - pCharacteristic = pService->createCharacteristic( - CHARACTERISTIC_UUID, - BLECharacteristic::PROPERTY_READ | - BLECharacteristic::PROPERTY_WRITE | - BLECharacteristic::PROPERTY_NOTIFY | - BLECharacteristic::PROPERTY_INDICATE - ); - - // https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.descriptor.gatt.client_characteristic_configuration.xml - // Create a BLE Descriptor - pCharacteristic->addDescriptor(new BLE2902()); - - // Start the service - pService->start(); - - // Start advertising - pServer->getAdvertising()->start(); - Serial.println("Waiting a client connection to notify..."); -} - -void loop() { - // notify changed value - if (deviceConnected) { - pCharacteristic->setValue(&value, 1); - pCharacteristic->notify(); - value++; - delay(10); // bluetooth stack will go into congestion, if too many packets are sent - } - // disconnecting - if (!deviceConnected && oldDeviceConnected) { - delay(500); // give the bluetooth stack the chance to get things ready - pServer->startAdvertising(); // restart advertising - Serial.println("start advertising"); - oldDeviceConnected = deviceConnected; - } - // connecting - if (deviceConnected && !oldDeviceConnected) { - // do stuff here on connecting - oldDeviceConnected = deviceConnected; - } -} \ No newline at end of file diff --git a/lib/ESP32_BLE_Arduino/examples/BLE_scan/BLE_scan.ino b/lib/ESP32_BLE_Arduino/examples/BLE_scan/BLE_scan.ino deleted file mode 100644 index ef7d8924..00000000 --- a/lib/ESP32_BLE_Arduino/examples/BLE_scan/BLE_scan.ino +++ /dev/null @@ -1,36 +0,0 @@ -/* - Based on Neil Kolban example for IDF: https://github.com/nkolban/esp32-snippets/blob/master/cpp_utils/tests/BLE%20Tests/SampleScan.cpp - Ported to Arduino ESP32 by Evandro Copercini -*/ - -#include -#include -#include -#include - -int scanTime = 30; //In seconds - -class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks { - void onResult(BLEAdvertisedDevice advertisedDevice) { - Serial.printf("Advertised Device: %s \n", advertisedDevice.toString().c_str()); - } -}; - -void setup() { - Serial.begin(115200); - Serial.println("Scanning..."); - - BLEDevice::init(""); - BLEScan* pBLEScan = BLEDevice::getScan(); //create new scan - pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks()); - pBLEScan->setActiveScan(true); //active scan uses more power, but get results faster - BLEScanResults foundDevices = pBLEScan->start(scanTime); - Serial.print("Devices found: "); - Serial.println(foundDevices.getCount()); - Serial.println("Scan done!"); -} - -void loop() { - // put your main code here, to run repeatedly: - delay(2000); -} \ No newline at end of file diff --git a/lib/ESP32_BLE_Arduino/examples/BLE_server/BLE_server.ino b/lib/ESP32_BLE_Arduino/examples/BLE_server/BLE_server.ino deleted file mode 100644 index 38224a67..00000000 --- a/lib/ESP32_BLE_Arduino/examples/BLE_server/BLE_server.ino +++ /dev/null @@ -1,39 +0,0 @@ -/* - Based on Neil Kolban example for IDF: https://github.com/nkolban/esp32-snippets/blob/master/cpp_utils/tests/BLE%20Tests/SampleServer.cpp - Ported to Arduino ESP32 by Evandro Copercini -*/ - -#include -#include -#include - -// See the following for generating UUIDs: -// https://www.uuidgenerator.net/ - -#define SERVICE_UUID "4fafc201-1fb5-459e-8fcc-c5c9c331914b" -#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8" - -void setup() { - Serial.begin(115200); - Serial.println("Starting BLE work!"); - - BLEDevice::init("MyESP32"); - BLEServer *pServer = BLEDevice::createServer(); - BLEService *pService = pServer->createService(SERVICE_UUID); - BLECharacteristic *pCharacteristic = pService->createCharacteristic( - CHARACTERISTIC_UUID, - BLECharacteristic::PROPERTY_READ | - BLECharacteristic::PROPERTY_WRITE - ); - - pCharacteristic->setValue("Hello World says Neil"); - pService->start(); - BLEAdvertising *pAdvertising = pServer->getAdvertising(); - pAdvertising->start(); - Serial.println("Characteristic defined! Now you can read it in your phone!"); -} - -void loop() { - // put your main code here, to run repeatedly: - delay(2000); -} \ No newline at end of file diff --git a/lib/ESP32_BLE_Arduino/examples/BLE_uart/BLE_uart.ino b/lib/ESP32_BLE_Arduino/examples/BLE_uart/BLE_uart.ino deleted file mode 100644 index 35b570b9..00000000 --- a/lib/ESP32_BLE_Arduino/examples/BLE_uart/BLE_uart.ino +++ /dev/null @@ -1,125 +0,0 @@ -/* - Video: https://www.youtube.com/watch?v=oCMOYS71NIU - Based on Neil Kolban example for IDF: https://github.com/nkolban/esp32-snippets/blob/master/cpp_utils/tests/BLE%20Tests/SampleNotify.cpp - Ported to Arduino ESP32 by Evandro Copercini - - Create a BLE server that, once we receive a connection, will send periodic notifications. - The service advertises itself as: 6E400001-B5A3-F393-E0A9-E50E24DCCA9E - Has a characteristic of: 6E400002-B5A3-F393-E0A9-E50E24DCCA9E - used for receiving data with "WRITE" - Has a characteristic of: 6E400003-B5A3-F393-E0A9-E50E24DCCA9E - used to send data with "NOTIFY" - - The design of creating the BLE server is: - 1. Create a BLE Server - 2. Create a BLE Service - 3. Create a BLE Characteristic on the Service - 4. Create a BLE Descriptor on the characteristic - 5. Start the service. - 6. Start advertising. - - In this example rxValue is the data received (only accessible inside that function). - And txValue is the data to be sent, in this example just a byte incremented every second. -*/ -#include -#include -#include -#include - -BLEServer *pServer = NULL; -BLECharacteristic * pTxCharacteristic; -bool deviceConnected = false; -bool oldDeviceConnected = false; -uint8_t txValue = 0; - -// See the following for generating UUIDs: -// https://www.uuidgenerator.net/ - -#define SERVICE_UUID "6E400001-B5A3-F393-E0A9-E50E24DCCA9E" // UART service UUID -#define CHARACTERISTIC_UUID_RX "6E400002-B5A3-F393-E0A9-E50E24DCCA9E" -#define CHARACTERISTIC_UUID_TX "6E400003-B5A3-F393-E0A9-E50E24DCCA9E" - - -class MyServerCallbacks: public BLEServerCallbacks { - void onConnect(BLEServer* pServer) { - deviceConnected = true; - }; - - void onDisconnect(BLEServer* pServer) { - deviceConnected = false; - } -}; - -class MyCallbacks: public BLECharacteristicCallbacks { - void onWrite(BLECharacteristic *pCharacteristic) { - std::string rxValue = pCharacteristic->getValue(); - - if (rxValue.length() > 0) { - Serial.println("*********"); - Serial.print("Received Value: "); - for (int i = 0; i < rxValue.length(); i++) - Serial.print(rxValue[i]); - - Serial.println(); - Serial.println("*********"); - } - } -}; - - -void setup() { - Serial.begin(115200); - - // Create the BLE Device - BLEDevice::init("UART Service"); - - // Create the BLE Server - pServer = BLEDevice::createServer(); - pServer->setCallbacks(new MyServerCallbacks()); - - // Create the BLE Service - BLEService *pService = pServer->createService(SERVICE_UUID); - - // Create a BLE Characteristic - pTxCharacteristic = pService->createCharacteristic( - CHARACTERISTIC_UUID_TX, - BLECharacteristic::PROPERTY_NOTIFY - ); - - pTxCharacteristic->addDescriptor(new BLE2902()); - - BLECharacteristic * pRxCharacteristic = pService->createCharacteristic( - CHARACTERISTIC_UUID_RX, - BLECharacteristic::PROPERTY_WRITE - ); - - pRxCharacteristic->setCallbacks(new MyCallbacks()); - - // Start the service - pService->start(); - - // Start advertising - pServer->getAdvertising()->start(); - Serial.println("Waiting a client connection to notify..."); -} - -void loop() { - - if (deviceConnected) { - pTxCharacteristic->setValue(&txValue, 1); - pTxCharacteristic->notify(); - txValue++; - delay(10); // bluetooth stack will go into congestion, if too many packets are sent - } - - // disconnecting - if (!deviceConnected && oldDeviceConnected) { - delay(500); // give the bluetooth stack the chance to get things ready - pServer->startAdvertising(); // restart advertising - Serial.println("start advertising"); - oldDeviceConnected = deviceConnected; - } - // connecting - if (deviceConnected && !oldDeviceConnected) { - // do stuff here on connecting - oldDeviceConnected = deviceConnected; - } -} diff --git a/lib/ESP32_BLE_Arduino/examples/BLE_write/BLE_write.ino b/lib/ESP32_BLE_Arduino/examples/BLE_write/BLE_write.ino deleted file mode 100644 index 24a0cd23..00000000 --- a/lib/ESP32_BLE_Arduino/examples/BLE_write/BLE_write.ino +++ /dev/null @@ -1,65 +0,0 @@ -/* - Based on Neil Kolban example for IDF: https://github.com/nkolban/esp32-snippets/blob/master/cpp_utils/tests/BLE%20Tests/SampleWrite.cpp - Ported to Arduino ESP32 by Evandro Copercini -*/ - -#include -#include -#include - -// See the following for generating UUIDs: -// https://www.uuidgenerator.net/ - -#define SERVICE_UUID "4fafc201-1fb5-459e-8fcc-c5c9c331914b" -#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8" - - -class MyCallbacks: public BLECharacteristicCallbacks { - void onWrite(BLECharacteristic *pCharacteristic) { - std::string value = pCharacteristic->getValue(); - - if (value.length() > 0) { - Serial.println("*********"); - Serial.print("New value: "); - for (int i = 0; i < value.length(); i++) - Serial.print(value[i]); - - Serial.println(); - Serial.println("*********"); - } - } -}; - -void setup() { - Serial.begin(115200); - - Serial.println("1- Download and install an BLE scanner app in your phone"); - Serial.println("2- Scan for BLE devices in the app"); - Serial.println("3- Connect to MyESP32"); - Serial.println("4- Go to CUSTOM CHARACTERISTIC in CUSTOM SERVICE and write something"); - Serial.println("5- See the magic =)"); - - BLEDevice::init("MyESP32"); - BLEServer *pServer = BLEDevice::createServer(); - - BLEService *pService = pServer->createService(SERVICE_UUID); - - BLECharacteristic *pCharacteristic = pService->createCharacteristic( - CHARACTERISTIC_UUID, - BLECharacteristic::PROPERTY_READ | - BLECharacteristic::PROPERTY_WRITE - ); - - pCharacteristic->setCallbacks(new MyCallbacks()); - - pCharacteristic->setValue("Hello World"); - pService->start(); - - BLEAdvertising *pAdvertising = pServer->getAdvertising(); - pAdvertising->start(); -} - -void loop() { - // put your main code here, to run repeatedly: - delay(2000); -} \ No newline at end of file diff --git a/lib/ESP32_BLE_Arduino/library.properties b/lib/ESP32_BLE_Arduino/library.properties deleted file mode 100644 index 23e642e9..00000000 --- a/lib/ESP32_BLE_Arduino/library.properties +++ /dev/null @@ -1,10 +0,0 @@ -name=ESP32 BLE Arduino -version=0.4.16 -author=Neil Kolban -maintainer=Neil Kolban -sentence=BLE functions for ESP32 -paragraph=This library provides an implementation Bluetooth Low Energy support for the ESP32 using the Arduino platform. -category=Communication -url=https://github.com/nkolban/ESP32_BLE_Arduino -architectures=esp32 -includes=BLE.h, BLEUtils.h, BLEScan.h, BLEAdvertisedDevice.h \ No newline at end of file diff --git a/lib/ESP32_BLE_Arduino/src/BLE2902.cpp b/lib/ESP32_BLE_Arduino/src/BLE2902.cpp deleted file mode 100644 index 8984da81..00000000 --- a/lib/ESP32_BLE_Arduino/src/BLE2902.cpp +++ /dev/null @@ -1,69 +0,0 @@ -/* - * BLE2902.cpp - * - * Created on: Jun 25, 2017 - * Author: kolban - */ - -/* - * See also: - * https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.descriptor.gatt.client_characteristic_configuration.xml - */ -#include "sdkconfig.h" -#if defined(CONFIG_BT_ENABLED) - -#include "BLE2902.h" - -BLE2902::BLE2902() : BLEDescriptor(BLEUUID((uint16_t) 0x2902)) { - uint8_t data[2] = {0,0}; - setValue(data, 2); -} // BLE2902 - - -/** - * @brief Get the notifications value. - * @return The notifications value. True if notifications are enabled and false if not. - */ -bool BLE2902::getNotifications() { - return (getValue()[0] & (1 << 0)) != 0; -} // getNotifications - - -/** - * @brief Get the indications value. - * @return The indications value. True if indications are enabled and false if not. - */ -bool BLE2902::getIndications() { - return (getValue()[0] & (1 << 1)) != 0; -} // getIndications - - -/** - * @brief Set the indications flag. - * @param [in] flag The indications flag. - */ -void BLE2902::setIndications(bool flag) { - uint8_t *pValue = getValue(); - if (flag) { - pValue[0] |= 1<<1; - } else { - pValue[0] &= ~(1<<1); - } -} // setIndications - - -/** - * @brief Set the notifications flag. - * @param [in] flag The notifications flag. - */ -void BLE2902::setNotifications(bool flag) { - uint8_t *pValue = getValue(); - if (flag) { - pValue[0] |= 1<<0; - } else { - pValue[0] &= ~(1<<0); - } -} // setNotifications - - -#endif diff --git a/lib/ESP32_BLE_Arduino/src/BLE2902.h b/lib/ESP32_BLE_Arduino/src/BLE2902.h deleted file mode 100644 index 397360ab..00000000 --- a/lib/ESP32_BLE_Arduino/src/BLE2902.h +++ /dev/null @@ -1,34 +0,0 @@ -/* - * BLE2902.h - * - * Created on: Jun 25, 2017 - * Author: kolban - */ - -#ifndef COMPONENTS_CPP_UTILS_BLE2902_H_ -#define COMPONENTS_CPP_UTILS_BLE2902_H_ -#include "sdkconfig.h" -#if defined(CONFIG_BT_ENABLED) - -#include "BLEDescriptor.h" - -/** - * @brief Descriptor for Client Characteristic Configuration. - * - * This is a convenience descriptor for the Client Characteristic Configuration which has a UUID of 0x2902. - * - * See also: - * https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.descriptor.gatt.client_characteristic_configuration.xml - */ -class BLE2902: public BLEDescriptor { -public: - BLE2902(); - bool getNotifications(); - bool getIndications(); - void setNotifications(bool flag); - void setIndications(bool flag); - -}; // BLE2902 - -#endif /* CONFIG_BT_ENABLED */ -#endif /* COMPONENTS_CPP_UTILS_BLE2902_H_ */ diff --git a/lib/ESP32_BLE_Arduino/src/BLE2904.cpp b/lib/ESP32_BLE_Arduino/src/BLE2904.cpp deleted file mode 100644 index 4423ed82..00000000 --- a/lib/ESP32_BLE_Arduino/src/BLE2904.cpp +++ /dev/null @@ -1,74 +0,0 @@ -/* - * BLE2904.cpp - * - * Created on: Dec 23, 2017 - * Author: kolban - */ - -/* - * See also: - * https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.descriptor.gatt.characteristic_presentation_format.xml - */ -#include "sdkconfig.h" -#if defined(CONFIG_BT_ENABLED) - -#include "BLE2904.h" - - -BLE2904::BLE2904() : BLEDescriptor(BLEUUID((uint16_t) 0x2904)) { - m_data.m_format = 0; - m_data.m_exponent = 0; - m_data.m_namespace = 1; // 1 = Bluetooth SIG Assigned Numbers - m_data.m_unit = 0; - m_data.m_description = 0; - setValue((uint8_t*)&m_data, sizeof(m_data)); -} // BLE2902 - - -/** - * @brief Set the description. - */ -void BLE2904::setDescription(uint16_t description) { - m_data.m_description = description; - setValue((uint8_t*)&m_data, sizeof(m_data)); -} - - -/** - * @brief Set the exponent. - */ -void BLE2904::setExponent(int8_t exponent) { - m_data.m_exponent = exponent; - setValue((uint8_t*)&m_data, sizeof(m_data)); -} // setExponent - - -/** - * @brief Set the format. - */ -void BLE2904::setFormat(uint8_t format) { - m_data.m_format = format; - setValue((uint8_t*)&m_data, sizeof(m_data)); -} // setFormat - - -/** - * @brief Set the namespace. - */ -void BLE2904::setNamespace(uint8_t namespace_value) { - m_data.m_namespace = namespace_value; - setValue((uint8_t*)&m_data, sizeof(m_data)); -} // setNamespace - - -/** - * @brief Set the units for this value. It should be one of the encoded values defined here: - * https://www.bluetooth.com/specifications/assigned-numbers/units - * @param [in] uint The type of units of this characteristic as defined by assigned numbers. - */ -void BLE2904::setUnit(uint16_t unit) { - m_data.m_unit = unit; - setValue((uint8_t*)&m_data, sizeof(m_data)); -} // setUnit - -#endif diff --git a/lib/ESP32_BLE_Arduino/src/BLE2904.h b/lib/ESP32_BLE_Arduino/src/BLE2904.h deleted file mode 100644 index cb337e22..00000000 --- a/lib/ESP32_BLE_Arduino/src/BLE2904.h +++ /dev/null @@ -1,74 +0,0 @@ -/* - * BLE2904.h - * - * Created on: Dec 23, 2017 - * Author: kolban - */ - -#ifndef COMPONENTS_CPP_UTILS_BLE2904_H_ -#define COMPONENTS_CPP_UTILS_BLE2904_H_ -#include "sdkconfig.h" -#if defined(CONFIG_BT_ENABLED) - -#include "BLEDescriptor.h" - -struct BLE2904_Data { - uint8_t m_format; - int8_t m_exponent; - uint16_t m_unit; // See https://www.bluetooth.com/specifications/assigned-numbers/units - uint8_t m_namespace; - uint16_t m_description; - -} __attribute__((packed)); - -/** - * @brief Descriptor for Characteristic Presentation Format. - * - * This is a convenience descriptor for the Characteristic Presentation Format which has a UUID of 0x2904. - * - * See also: - * https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.descriptor.gatt.characteristic_presentation_format.xml - */ -class BLE2904: public BLEDescriptor { -public: - BLE2904(); - static const uint8_t FORMAT_BOOLEAN = 1; - static const uint8_t FORMAT_UINT2 = 2; - static const uint8_t FORMAT_UINT4 = 3; - static const uint8_t FORMAT_UINT8 = 4; - static const uint8_t FORMAT_UINT12 = 5; - static const uint8_t FORMAT_UINT16 = 6; - static const uint8_t FORMAT_UINT24 = 7; - static const uint8_t FORMAT_UINT32 = 8; - static const uint8_t FORMAT_UINT48 = 9; - static const uint8_t FORMAT_UINT64 = 10; - static const uint8_t FORMAT_UINT128 = 11; - static const uint8_t FORMAT_SINT8 = 12; - static const uint8_t FORMAT_SINT12 = 13; - static const uint8_t FORMAT_SINT16 = 14; - static const uint8_t FORMAT_SINT24 = 15; - static const uint8_t FORMAT_SINT32 = 16; - static const uint8_t FORMAT_SINT48 = 17; - static const uint8_t FORMAT_SINT64 = 18; - static const uint8_t FORMAT_SINT128 = 19; - static const uint8_t FORMAT_FLOAT32 = 20; - static const uint8_t FORMAT_FLOAT64 = 21; - static const uint8_t FORMAT_SFLOAT16 = 22; - static const uint8_t FORMAT_SFLOAT32 = 23; - static const uint8_t FORMAT_IEEE20601 = 24; - static const uint8_t FORMAT_UTF8 = 25; - static const uint8_t FORMAT_UTF16 = 26; - static const uint8_t FORMAT_OPAQUE = 27; - - void setDescription(uint16_t); - void setExponent(int8_t exponent); - void setFormat(uint8_t format); - void setNamespace(uint8_t namespace_value); - void setUnit(uint16_t unit); - -private: - BLE2904_Data m_data; -}; // BLE2904 - -#endif /* CONFIG_BT_ENABLED */ -#endif /* COMPONENTS_CPP_UTILS_BLE2904_H_ */ diff --git a/lib/ESP32_BLE_Arduino/src/BLEAddress.cpp b/lib/ESP32_BLE_Arduino/src/BLEAddress.cpp deleted file mode 100644 index 895fedad..00000000 --- a/lib/ESP32_BLE_Arduino/src/BLEAddress.cpp +++ /dev/null @@ -1,96 +0,0 @@ -/* - * BLEAddress.cpp - * - * Created on: Jul 2, 2017 - * Author: kolban - */ -#include "sdkconfig.h" -#if defined(CONFIG_BT_ENABLED) - -#include "BLEAddress.h" -#include -#include -#include -#include -#include -#ifdef ARDUINO_ARCH_ESP32 -#include "esp32-hal-log.h" -#endif - - -/** - * @brief Create an address from the native ESP32 representation. - * @param [in] address The native representation. - */ -BLEAddress::BLEAddress(esp_bd_addr_t address) { - memcpy(m_address, address, ESP_BD_ADDR_LEN); -} // BLEAddress - - -/** - * @brief Create an address from a hex string - * - * A hex string is of the format: - * ``` - * 00:00:00:00:00:00 - * ``` - * which is 17 characters in length. - * - * @param [in] stringAddress The hex representation of the address. - */ -BLEAddress::BLEAddress(std::string stringAddress) { - if (stringAddress.length() != 17) { - return; - } - int data[6]; - sscanf(stringAddress.c_str(), "%x:%x:%x:%x:%x:%x", &data[0], &data[1], &data[2], &data[3], &data[4], &data[5]); - m_address[0] = (uint8_t)data[0]; - m_address[1] = (uint8_t)data[1]; - m_address[2] = (uint8_t)data[2]; - m_address[3] = (uint8_t)data[3]; - m_address[4] = (uint8_t)data[4]; - m_address[5] = (uint8_t)data[5]; -} // BLEAddress - - -/** - * @brief Determine if this address equals another. - * @param [in] otherAddress The other address to compare against. - * @return True if the addresses are equal. - */ -bool BLEAddress::equals(BLEAddress otherAddress) { - return memcmp(otherAddress.getNative(), m_address, 6) == 0; -} // equals - - -/** - * @brief Return the native representation of the address. - * @return The native representation of the address. - */ -esp_bd_addr_t *BLEAddress::getNative() { - return &m_address; -} // getNative - - -/** - * @brief Convert a BLE address to a string. - * - * A string representation of an address is in the format: - * - * ``` - * xx:xx:xx:xx:xx:xx - * ``` - * - * @return The string representation of the address. - */ -std::string BLEAddress::toString() { - std::stringstream stream; - stream << std::setfill('0') << std::setw(2) << std::hex << (int)((uint8_t *)(m_address))[0] << ':'; - stream << std::setfill('0') << std::setw(2) << std::hex << (int)((uint8_t *)(m_address))[1] << ':'; - stream << std::setfill('0') << std::setw(2) << std::hex << (int)((uint8_t *)(m_address))[2] << ':'; - stream << std::setfill('0') << std::setw(2) << std::hex << (int)((uint8_t *)(m_address))[3] << ':'; - stream << std::setfill('0') << std::setw(2) << std::hex << (int)((uint8_t *)(m_address))[4] << ':'; - stream << std::setfill('0') << std::setw(2) << std::hex << (int)((uint8_t *)(m_address))[5]; - return stream.str(); -} // toString -#endif diff --git a/lib/ESP32_BLE_Arduino/src/BLEAddress.h b/lib/ESP32_BLE_Arduino/src/BLEAddress.h deleted file mode 100644 index 7eff4da4..00000000 --- a/lib/ESP32_BLE_Arduino/src/BLEAddress.h +++ /dev/null @@ -1,34 +0,0 @@ -/* - * BLEAddress.h - * - * Created on: Jul 2, 2017 - * Author: kolban - */ - -#ifndef COMPONENTS_CPP_UTILS_BLEADDRESS_H_ -#define COMPONENTS_CPP_UTILS_BLEADDRESS_H_ -#include "sdkconfig.h" -#if defined(CONFIG_BT_ENABLED) -#include // ESP32 BLE -#include - - -/** - * @brief A %BLE device address. - * - * Every %BLE device has a unique address which can be used to identify it and form connections. - */ -class BLEAddress { -public: - BLEAddress(esp_bd_addr_t address); - BLEAddress(std::string stringAddress); - bool equals(BLEAddress otherAddress); - esp_bd_addr_t* getNative(); - std::string toString(); - -private: - esp_bd_addr_t m_address; -}; - -#endif /* CONFIG_BT_ENABLED */ -#endif /* COMPONENTS_CPP_UTILS_BLEADDRESS_H_ */ diff --git a/lib/ESP32_BLE_Arduino/src/BLEAdvertisedDevice.cpp b/lib/ESP32_BLE_Arduino/src/BLEAdvertisedDevice.cpp deleted file mode 100644 index 3b2532d8..00000000 --- a/lib/ESP32_BLE_Arduino/src/BLEAdvertisedDevice.cpp +++ /dev/null @@ -1,534 +0,0 @@ -/* - * BLEAdvertisedDevice.cpp - * - * During the scanning procedure, we will be finding advertised BLE devices. This class - * models a found device. - * - * - * See also: - * https://www.bluetooth.com/specifications/assigned-numbers/generic-access-profile - * - * Created on: Jul 3, 2017 - * Author: kolban - */ -#include "sdkconfig.h" -#if defined(CONFIG_BT_ENABLED) -#include -#include -#include "BLEAdvertisedDevice.h" -#include "BLEUtils.h" -#ifdef ARDUINO_ARCH_ESP32 -#include "esp32-hal-log.h" -#endif -static const char* LOG_TAG="BLEAdvertisedDevice"; - -BLEAdvertisedDevice::BLEAdvertisedDevice() { - m_adFlag = 0; - m_appearance = 0; - m_deviceType = 0; - m_manufacturerData = ""; - m_name = ""; - m_rssi = -9999; - m_txPower = 0; - m_pScan = nullptr; - - m_haveAppearance = false; - m_haveManufacturerData = false; - m_haveName = false; - m_haveRSSI = false; - m_haveServiceData = false; - m_haveServiceUUID = false; - m_haveTXPower = false; - -} // BLEAdvertisedDevice - - -/** - * @brief Get the address. - * - * Every %BLE device exposes an address that is used to identify it and subsequently connect to it. - * Call this function to obtain the address of the advertised device. - * - * @return The address of the advertised device. - */ -BLEAddress BLEAdvertisedDevice::getAddress() { - return m_address; -} // getAddress - - -/** - * @brief Get the appearance. - * - * A %BLE device can declare its own appearance. The appearance is how it would like to be shown to an end user - * typcially in the form of an icon. - * - * @return The appearance of the advertised device. - */ -uint16_t BLEAdvertisedDevice::getAppearance() { - return m_appearance; -} // getAppearance - - -/** - * @brief Get the manufacturer data. - * @return The manufacturer data of the advertised device. - */ -std::string BLEAdvertisedDevice::getManufacturerData() { - return m_manufacturerData; -} // getManufacturerData - - -/** - * @brief Get the name. - * @return The name of the advertised device. - */ -std::string BLEAdvertisedDevice::getName() { - return m_name; -} // getName - - -/** - * @brief Get the RSSI. - * @return The RSSI of the advertised device. - */ -int BLEAdvertisedDevice::getRSSI() { - return m_rssi; -} // getRSSI - - -/** - * @brief Get the scan object that created this advertisement. - * @return The scan object. - */ -BLEScan* BLEAdvertisedDevice::getScan() { - return m_pScan; -} // getScan - - -/** - * @brief Get the number of service data. - * @return Number of service data discovered. - */ -int BLEAdvertisedDevice::getServiceDataCount() { - if (m_haveServiceData) - return m_serviceDataVector.size(); - else - return 0; - -} //getServiceDataCount - -/** - * @brief Get the service data. - * @return The ServiceData of the advertised device. - */ -std::string BLEAdvertisedDevice::getServiceData(int i) { - return m_serviceDataVector[i]; -} //getServiceData - - -/** - * @brief Get the service data UUID. - * @return The service data UUID. - */ -BLEUUID BLEAdvertisedDevice::getServiceDataUUID(int i) { - return m_serviceDataUUIDs[i]; -} // getServiceDataUUID - - -/** - * @brief Get the Service UUID. - * @return The Service UUID of the advertised device. - */ -BLEUUID BLEAdvertisedDevice::getServiceUUID(int i) { - return m_serviceUUIDs[i]; -} // getServiceUUID - -/** - * @brief Check advertised serviced for existence required UUID - * @return Return true if service is advertised - */ -bool BLEAdvertisedDevice::isAdvertisingService(BLEUUID uuid){ - for (int i = 0; i < m_serviceUUIDs.size(); ++i) { - if(m_serviceUUIDs[i].equals(uuid)) - return true; - } - return false; -} - -/** - * @brief Get the TX Power. - * @return The TX Power of the advertised device. - */ -int8_t BLEAdvertisedDevice::getTXPower() { - return m_txPower; -} // getTXPower - - - -/** - * @brief Does this advertisement have an appearance value? - * @return True if there is an appearance value present. - */ -bool BLEAdvertisedDevice::haveAppearance() { - return m_haveAppearance; -} // haveAppearance - - -/** - * @brief Does this advertisement have manufacturer data? - * @return True if there is manufacturer data present. - */ -bool BLEAdvertisedDevice::haveManufacturerData() { - return m_haveManufacturerData; -} // haveManufacturerData - - -/** - * @brief Does this advertisement have a name value? - * @return True if there is a name value present. - */ -bool BLEAdvertisedDevice::haveName() { - return m_haveName; -} // haveName - - -/** - * @brief Does this advertisement have a signal strength value? - * @return True if there is a signal strength value present. - */ -bool BLEAdvertisedDevice::haveRSSI() { - return m_haveRSSI; -} // haveRSSI - - -/** - * @brief Does this advertisement have a service data value? - * @return True if there is a service data value present. - */ -bool BLEAdvertisedDevice::haveServiceData() { - return m_haveServiceData; -} // haveServiceData - - -/** - * @brief Does this advertisement have a service UUID value? - * @return True if there is a service UUID value present. - */ -bool BLEAdvertisedDevice::haveServiceUUID() { - return m_haveServiceUUID; -} // haveServiceUUID - - -/** - * @brief Does this advertisement have a transmission power value? - * @return True if there is a transmission power value present. - */ -bool BLEAdvertisedDevice::haveTXPower() { - return m_haveTXPower; -} // haveTXPower - - -/** - * @brief Parse the advertising pay load. - * - * The pay load is a buffer of bytes that is either 31 bytes long or terminated by - * a 0 length value. Each entry in the buffer has the format: - * [length][type][data...] - * - * The length does not include itself but does include everything after it until the next record. A record - * with a length value of 0 indicates a terminator. - * - * https://www.bluetooth.com/specifications/assigned-numbers/generic-access-profile - */ -void BLEAdvertisedDevice::parseAdvertisement(uint8_t* payload) { - uint8_t length; - uint8_t ad_type; - uint8_t sizeConsumed = 0; - bool finished = false; - setPayload(payload); - - while(!finished) { - length = *payload; // Retrieve the length of the record. - payload++; // Skip to type - sizeConsumed += 1 + length; // increase the size consumed. - - if (length != 0) { // A length of 0 indicates that we have reached the end. - ad_type = *payload; - payload++; - length--; - - char* pHex = BLEUtils::buildHexData(nullptr, payload, length); - ESP_LOGD(LOG_TAG, "Type: 0x%.2x (%s), length: %d, data: %s", - ad_type, BLEUtils::advTypeToString(ad_type), length, pHex); - free(pHex); - - switch(ad_type) { - case ESP_BLE_AD_TYPE_NAME_CMPL: { // Adv Data Type: 0x09 - setName(std::string(reinterpret_cast(payload), length)); - break; - } // ESP_BLE_AD_TYPE_NAME_CMPL - - case ESP_BLE_AD_TYPE_TX_PWR: { // Adv Data Type: 0x0A - setTXPower(*payload); - break; - } // ESP_BLE_AD_TYPE_TX_PWR - - case ESP_BLE_AD_TYPE_APPEARANCE: { // Adv Data Type: 0x19 - setAppearance(*reinterpret_cast(payload)); - break; - } // ESP_BLE_AD_TYPE_APPEARANCE - - case ESP_BLE_AD_TYPE_FLAG: { // Adv Data Type: 0x01 - setAdFlag(*payload); - break; - } // ESP_BLE_AD_TYPE_FLAG - - case ESP_BLE_AD_TYPE_16SRV_CMPL: - case ESP_BLE_AD_TYPE_16SRV_PART: { // Adv Data Type: 0x02 - for (int var = 0; var < length/2; ++var) { - setServiceUUID(BLEUUID(*reinterpret_cast(payload+var*2))); - } - break; - } // ESP_BLE_AD_TYPE_16SRV_PART - - case ESP_BLE_AD_TYPE_32SRV_CMPL: - case ESP_BLE_AD_TYPE_32SRV_PART: { // Adv Data Type: 0x04 - for (int var = 0; var < length/4; ++var) { - setServiceUUID(BLEUUID(*reinterpret_cast(payload+var*4))); - } - break; - } // ESP_BLE_AD_TYPE_32SRV_PART - - case ESP_BLE_AD_TYPE_128SRV_CMPL: { // Adv Data Type: 0x07 - setServiceUUID(BLEUUID(payload, 16, false)); - break; - } // ESP_BLE_AD_TYPE_128SRV_CMPL - - case ESP_BLE_AD_TYPE_128SRV_PART: { // Adv Data Type: 0x06 - setServiceUUID(BLEUUID(payload, 16, false)); - break; - } // ESP_BLE_AD_TYPE_128SRV_PART - - // See CSS Part A 1.4 Manufacturer Specific Data - case ESP_BLE_AD_MANUFACTURER_SPECIFIC_TYPE: { - setManufacturerData(std::string(reinterpret_cast(payload), length)); - break; - } // ESP_BLE_AD_MANUFACTURER_SPECIFIC_TYPE - - case ESP_BLE_AD_TYPE_SERVICE_DATA: { // Adv Data Type: 0x16 (Service Data) - 2 byte UUID - if (length < 2) { - ESP_LOGE(LOG_TAG, "Length too small for ESP_BLE_AD_TYPE_SERVICE_DATA"); - break; - } - uint16_t uuid = *(uint16_t *)payload; - setServiceDataUUID(BLEUUID(uuid)); - if (length > 2) { - setServiceData(std::string(reinterpret_cast(payload+2), length-2)); - } - break; - } //ESP_BLE_AD_TYPE_SERVICE_DATA - - case ESP_BLE_AD_TYPE_32SERVICE_DATA: { // Adv Data Type: 0x20 (Service Data) - 4 byte UUID - if (length < 4) { - ESP_LOGE(LOG_TAG, "Length too small for ESP_BLE_AD_TYPE_32SERVICE_DATA"); - break; - } - uint32_t uuid = *(uint32_t *)payload; - setServiceDataUUID(BLEUUID(uuid)); - if (length > 4) { - setServiceData(std::string(reinterpret_cast(payload+4), length-4)); - } - break; - } //ESP_BLE_AD_TYPE_32SERVICE_DATA - - case ESP_BLE_AD_TYPE_128SERVICE_DATA: { // Adv Data Type: 0x21 (Service Data) - 16 byte UUID - if (length < 16) { - ESP_LOGE(LOG_TAG, "Length too small for ESP_BLE_AD_TYPE_128SERVICE_DATA"); - break; - } - - setServiceDataUUID(BLEUUID(payload, (size_t)16, false)); - if (length > 16) { - setServiceData(std::string(reinterpret_cast(payload+16), length-16)); - } - break; - } //ESP_BLE_AD_TYPE_32SERVICE_DATA - - default: { - ESP_LOGD(LOG_TAG, "Unhandled type: adType: %d - 0x%.2x", ad_type, ad_type); - break; - } - } // switch - payload += length; - } // Length <> 0 - - - if (sizeConsumed >=31 || length == 0) { - finished = true; - } - } // !finished -} // parseAdvertisement - - -/** - * @brief Set the address of the advertised device. - * @param [in] address The address of the advertised device. - */ -void BLEAdvertisedDevice::setAddress(BLEAddress address) { - m_address = address; -} // setAddress - - -/** - * @brief Set the adFlag for this device. - * @param [in] The discovered adFlag. - */ -void BLEAdvertisedDevice::setAdFlag(uint8_t adFlag) { - m_adFlag = adFlag; -} // setAdFlag - - -/** - * @brief Set the appearance for this device. - * @param [in] The discovered appearance. - */ -void BLEAdvertisedDevice::setAppearance(uint16_t appearance) { - m_appearance = appearance; - m_haveAppearance = true; - ESP_LOGD(LOG_TAG, "- appearance: %d", m_appearance); -} // setAppearance - - -/** - * @brief Set the manufacturer data for this device. - * @param [in] The discovered manufacturer data. - */ -void BLEAdvertisedDevice::setManufacturerData(std::string manufacturerData) { - m_manufacturerData = manufacturerData; - m_haveManufacturerData = true; - char* pHex = BLEUtils::buildHexData(nullptr, (uint8_t*)m_manufacturerData.data(), (uint8_t)m_manufacturerData.length()); - ESP_LOGD(LOG_TAG, "- manufacturer data: %s", pHex); - free(pHex); -} // setManufacturerData - - -/** - * @brief Set the name for this device. - * @param [in] name The discovered name. - */ -void BLEAdvertisedDevice::setName(std::string name) { - m_name = name; - m_haveName = true; - ESP_LOGD(LOG_TAG, "- setName(): name: %s", m_name.c_str()); -} // setName - - -/** - * @brief Set the RSSI for this device. - * @param [in] rssi The discovered RSSI. - */ -void BLEAdvertisedDevice::setRSSI(int rssi) { - m_rssi = rssi; - m_haveRSSI = true; - ESP_LOGD(LOG_TAG, "- setRSSI(): rssi: %d", m_rssi); -} // setRSSI - - -/** - * @brief Set the Scan that created this advertised device. - * @param pScan The Scan that created this advertised device. - */ -void BLEAdvertisedDevice::setScan(BLEScan* pScan) { - m_pScan = pScan; -} // setScan - - -/** - * @brief Set the Service UUID for this device. - * @param [in] serviceUUID The discovered serviceUUID - */ -void BLEAdvertisedDevice::setServiceUUID(const char* serviceUUID) { - return setServiceUUID(BLEUUID(serviceUUID)); -} // setServiceUUID - - -/** - * @brief Set the Service UUID for this device. - * @param [in] serviceUUID The discovered serviceUUID - */ -void BLEAdvertisedDevice::setServiceUUID(BLEUUID serviceUUID) { - m_serviceUUIDs.push_back(serviceUUID); - m_haveServiceUUID = true; - ESP_LOGD(LOG_TAG, "- addServiceUUID(): serviceUUID: %s", serviceUUID.toString().c_str()); -} // setServiceUUID - - -/** - * @brief Set the ServiceData value. - * @param [in] data ServiceData value. - */ -void BLEAdvertisedDevice::setServiceData(std::string serviceData) { - m_haveServiceData = true; // Set the flag that indicates we have service data. - m_serviceDataVector.push_back(serviceData); // Save the service data that we received. -} //setServiceData - - -/** - * @brief Set the ServiceDataUUID value. - * @param [in] data ServiceDataUUID value. - */ -void BLEAdvertisedDevice::setServiceDataUUID(BLEUUID uuid) { - m_haveServiceData = true; // Set the flag that indicates we have service data. - m_serviceDataUUIDs.push_back(uuid); - ESP_LOGD(LOG_TAG, "- addServiceDataUUID(): serviceDataUUID: %s", uuid.toString().c_str()); -} // setServiceDataUUID - - -/** - * @brief Set the power level for this device. - * @param [in] txPower The discovered power level. - */ -void BLEAdvertisedDevice::setTXPower(int8_t txPower) { - m_txPower = txPower; - m_haveTXPower = true; - ESP_LOGD(LOG_TAG, "- txPower: %d", m_txPower); -} // setTXPower - - -/** - * @brief Create a string representation of this device. - * @return A string representation of this device. - */ -std::string BLEAdvertisedDevice::toString() { - std::stringstream ss; - ss << "Name: " << getName() << ", Address: " << getAddress().toString(); - if (haveAppearance()) { - ss << ", appearance: " << getAppearance(); - } - if (haveManufacturerData()) { - char *pHex = BLEUtils::buildHexData(nullptr, (uint8_t*)getManufacturerData().data(), getManufacturerData().length()); - ss << ", manufacturer data: " << pHex; - free(pHex); - } - if (haveServiceUUID()) { - for (int i; i < m_serviceUUIDs.size(); i++) { - ss << ", serviceUUID: " << getServiceUUID(i).toString(); - } - } - if (haveTXPower()) { - ss << ", txPower: " << (int)getTXPower(); - } - return ss.str(); -} // toString - -uint8_t* BLEAdvertisedDevice::getPayload() { - return m_payload; -} - -void BLEAdvertisedDevice::setPayload(uint8_t* payload) { - m_payload = payload; -} - - -#endif /* CONFIG_BT_ENABLED */ - diff --git a/lib/ESP32_BLE_Arduino/src/BLEAdvertisedDevice.h b/lib/ESP32_BLE_Arduino/src/BLEAdvertisedDevice.h deleted file mode 100644 index 98a40d3a..00000000 --- a/lib/ESP32_BLE_Arduino/src/BLEAdvertisedDevice.h +++ /dev/null @@ -1,121 +0,0 @@ -/* - * BLEAdvertisedDevice.h - * - * Created on: Jul 3, 2017 - * Author: kolban - */ - -#ifndef COMPONENTS_CPP_UTILS_BLEADVERTISEDDEVICE_H_ -#define COMPONENTS_CPP_UTILS_BLEADVERTISEDDEVICE_H_ -#include "sdkconfig.h" -#if defined(CONFIG_BT_ENABLED) -#include - -#include - -#include "BLEAddress.h" -#include "BLEScan.h" -#include "BLEUUID.h" - - -class BLEScan; -/** - * @brief A representation of a %BLE advertised device found by a scan. - * - * When we perform a %BLE scan, the result will be a set of devices that are advertising. This - * class provides a model of a detected device. - */ -class BLEAdvertisedDevice { -public: - BLEAdvertisedDevice(); - - BLEAddress getAddress(); - uint16_t getAppearance(); - std::string getManufacturerData(); - std::string getName(); - int getRSSI(); - BLEScan* getScan(); - std::string getServiceData(int i); - BLEUUID getServiceDataUUID(int i); - BLEUUID getServiceUUID(int i); - int getServiceDataCount(); - int8_t getTXPower(); - uint8_t* getPayload(); - - - bool isAdvertisingService(BLEUUID uuid); - bool haveAppearance(); - bool haveManufacturerData(); - bool haveName(); - bool haveRSSI(); - bool haveServiceData(); - bool haveServiceUUID(); - bool haveTXPower(); - - std::string toString(); - -private: - friend class BLEScan; - - void parseAdvertisement(uint8_t* payload); - void setAddress(BLEAddress address); - void setAdFlag(uint8_t adFlag); - void setAdvertizementResult(uint8_t* payload); - void setAppearance(uint16_t appearance); - void setManufacturerData(std::string manufacturerData); - void setName(std::string name); - void setRSSI(int rssi); - void setScan(BLEScan* pScan); - void setServiceData(std::string data); - void setServiceDataUUID(BLEUUID uuid); - void setServiceUUID(const char* serviceUUID); - void setServiceUUID(BLEUUID serviceUUID); - void setTXPower(int8_t txPower); - void setPayload(uint8_t* payload); - - - bool m_haveAppearance; - bool m_haveManufacturerData; - bool m_haveName; - bool m_haveRSSI; - bool m_haveServiceData; - bool m_haveServiceUUID; - bool m_haveTXPower; - - - BLEAddress m_address = BLEAddress((uint8_t*)"\0\0\0\0\0\0"); - uint8_t m_adFlag; - uint16_t m_appearance; - int m_deviceType; - std::string m_manufacturerData; - std::string m_name; - BLEScan* m_pScan; - int m_rssi; - std::vector m_serviceUUIDs; - std::vector m_serviceDataUUIDs; - std::vector m_serviceDataVector; - int8_t m_txPower; - uint8_t* m_payload; -}; - -/** - * @brief A callback handler for callbacks associated device scanning. - * - * When we are performing a scan as a %BLE client, we may wish to know when a new device that is advertising - * has been found. This class can be sub-classed and registered such that when a scan is performed and - * a new advertised device has been found, we will be called back to be notified. - */ -class BLEAdvertisedDeviceCallbacks { -public: - virtual ~BLEAdvertisedDeviceCallbacks() {} - /** - * @brief Called when a new scan result is detected. - * - * As we are scanning, we will find new devices. When found, this call back is invoked with a reference to the - * device that was found. During any individual scan, a device will only be detected one time. - */ - virtual void onResult(BLEAdvertisedDevice advertisedDevice) = 0; -}; - -#endif /* CONFIG_BT_ENABLED */ -#endif /* COMPONENTS_CPP_UTILS_BLEADVERTISEDDEVICE_H_ */ diff --git a/lib/ESP32_BLE_Arduino/src/BLEAdvertising.cpp b/lib/ESP32_BLE_Arduino/src/BLEAdvertising.cpp deleted file mode 100644 index 4b3cb8d6..00000000 --- a/lib/ESP32_BLE_Arduino/src/BLEAdvertising.cpp +++ /dev/null @@ -1,462 +0,0 @@ -/* - * BLEAdvertising.cpp - * - * This class encapsulates advertising a BLE Server. - * Created on: Jun 21, 2017 - * Author: kolban - * - * The ESP-IDF provides a framework for BLE advertising. It has determined that there are a common set - * of properties that are advertised and has built a data structure that can be populated by the programmer. - * This means that the programmer doesn't have to "mess with" the low level construction of a low level - * BLE advertising frame. Many of the fields are determined for us while others we can set before starting - * to advertise. - * - * Should we wish to construct our own payload, we can use the BLEAdvertisementData class and call the setters - * upon it. Once it is populated, we can then associate it with the advertising and what ever the programmer - * set in the data will be advertised. - * - */ -#include "sdkconfig.h" -#if defined(CONFIG_BT_ENABLED) -#include "BLEAdvertising.h" -#include -#include -#include "BLEUtils.h" -#include "GeneralUtils.h" - -#ifdef ARDUINO_ARCH_ESP32 -#include "esp32-hal-log.h" -#endif - -static const char* LOG_TAG = "BLEAdvertising"; - - -/** - * @brief Construct a default advertising object. - * - */ -BLEAdvertising::BLEAdvertising() { - m_advData.set_scan_rsp = false; - m_advData.include_name = true; - m_advData.include_txpower = true; - m_advData.min_interval = 0x20; - m_advData.max_interval = 0x40; - m_advData.appearance = 0x00; - m_advData.manufacturer_len = 0; - m_advData.p_manufacturer_data = nullptr; - m_advData.service_data_len = 0; - m_advData.p_service_data = nullptr; - m_advData.service_uuid_len = 0; - m_advData.p_service_uuid = nullptr; - m_advData.flag = (ESP_BLE_ADV_FLAG_GEN_DISC | ESP_BLE_ADV_FLAG_BREDR_NOT_SPT); - - m_advParams.adv_int_min = 0x20; - m_advParams.adv_int_max = 0x40; - m_advParams.adv_type = ADV_TYPE_IND; - m_advParams.own_addr_type = BLE_ADDR_TYPE_PUBLIC; - m_advParams.channel_map = ADV_CHNL_ALL; - m_advParams.adv_filter_policy = ADV_FILTER_ALLOW_SCAN_ANY_CON_ANY; - - m_customAdvData = false; // No custom advertising data - m_customScanResponseData = false; // No custom scan response data -} // BLEAdvertising - - -/** - * @brief Add a service uuid to exposed list of services. - * @param [in] serviceUUID The UUID of the service to expose. - */ -void BLEAdvertising::addServiceUUID(BLEUUID serviceUUID) { - m_serviceUUIDs.push_back(serviceUUID); -} // addServiceUUID - - -/** - * @brief Add a service uuid to exposed list of services. - * @param [in] serviceUUID The string representation of the service to expose. - */ -void BLEAdvertising::addServiceUUID(const char* serviceUUID) { - addServiceUUID(BLEUUID(serviceUUID)); -} // addServiceUUID - - -/** - * @brief Set the device appearance in the advertising data. - * The appearance attribute is of type 0x19. The codes for distinct appearances can be found here: - * https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.gap.appearance.xml. - * @param [in] appearance The appearance of the device in the advertising data. - * @return N/A. - */ -void BLEAdvertising::setAppearance(uint16_t appearance) { - m_advData.appearance = appearance; -} // setAppearance - -void BLEAdvertising::setMinInterval(uint16_t mininterval) { - m_advData.min_interval = mininterval; - m_advParams.adv_int_min = mininterval; -} // setMinInterval - -void BLEAdvertising::setMaxInterval(uint16_t maxinterval) { - m_advData.max_interval = maxinterval; - m_advParams.adv_int_max = maxinterval; -} // setMaxInterval - - -/** - * @brief Set the filtering for the scan filter. - * @param [in] scanRequestWhitelistOnly If true, only allow scan requests from those on the white list. - * @param [in] connectWhitelistOnly If true, only allow connections from those on the white list. - */ -void BLEAdvertising::setScanFilter(bool scanRequestWhitelistOnly, bool connectWhitelistOnly) { - ESP_LOGD(LOG_TAG, ">> setScanFilter: scanRequestWhitelistOnly: %d, connectWhitelistOnly: %d", scanRequestWhitelistOnly, connectWhitelistOnly); - if (!scanRequestWhitelistOnly && !connectWhitelistOnly) { - m_advParams.adv_filter_policy = ADV_FILTER_ALLOW_SCAN_ANY_CON_ANY; - ESP_LOGD(LOG_TAG, "<< setScanFilter"); - return; - } - if (scanRequestWhitelistOnly && !connectWhitelistOnly) { - m_advParams.adv_filter_policy = ADV_FILTER_ALLOW_SCAN_WLST_CON_ANY; - ESP_LOGD(LOG_TAG, "<< setScanFilter"); - return; - } - if (!scanRequestWhitelistOnly && connectWhitelistOnly) { - m_advParams.adv_filter_policy = ADV_FILTER_ALLOW_SCAN_ANY_CON_WLST; - ESP_LOGD(LOG_TAG, "<< setScanFilter"); - return; - } - if (scanRequestWhitelistOnly && connectWhitelistOnly) { - m_advParams.adv_filter_policy = ADV_FILTER_ALLOW_SCAN_WLST_CON_WLST; - ESP_LOGD(LOG_TAG, "<< setScanFilter"); - return; - } -} // setScanFilter - - -/** - * @brief Set the advertisement data that is to be published in a regular advertisement. - * @param [in] advertisementData The data to be advertised. - */ -void BLEAdvertising::setAdvertisementData(BLEAdvertisementData& advertisementData) { - ESP_LOGD(LOG_TAG, ">> setAdvertisementData"); - esp_err_t errRc = ::esp_ble_gap_config_adv_data_raw( - (uint8_t*)advertisementData.getPayload().data(), - advertisementData.getPayload().length()); - if (errRc != ESP_OK) { - ESP_LOGE(LOG_TAG, "esp_ble_gap_config_adv_data_raw: %d %s", errRc, GeneralUtils::errorToString(errRc)); - } - m_customAdvData = true; // Set the flag that indicates we are using custom advertising data. - ESP_LOGD(LOG_TAG, "<< setAdvertisementData"); -} // setAdvertisementData - - -/** - * @brief Set the advertisement data that is to be published in a scan response. - * @param [in] advertisementData The data to be advertised. - */ -void BLEAdvertising::setScanResponseData(BLEAdvertisementData& advertisementData) { - ESP_LOGD(LOG_TAG, ">> setScanResponseData"); - esp_err_t errRc = ::esp_ble_gap_config_scan_rsp_data_raw( - (uint8_t*)advertisementData.getPayload().data(), - advertisementData.getPayload().length()); - if (errRc != ESP_OK) { - ESP_LOGE(LOG_TAG, "esp_ble_gap_config_scan_rsp_data_raw: %d %s", errRc, GeneralUtils::errorToString(errRc)); - } - m_customScanResponseData = true; // Set the flag that indicates we are using custom scan response data. - ESP_LOGD(LOG_TAG, "<< setScanResponseData"); -} // setScanResponseData - -/** - * @brief Start advertising. - * Start advertising. - * @return N/A. - */ -void BLEAdvertising::start() { - ESP_LOGD(LOG_TAG, ">> start: customAdvData: %d, customScanResponseData: %d", m_customAdvData, m_customScanResponseData); - - - // We have a vector of service UUIDs that we wish to advertise. In order to use the - // ESP-IDF framework, these must be supplied in a contiguous array of their 128bit (16 byte) - // representations. If we have 1 or more services to advertise then we allocate enough - // storage to host them and then copy them in one at a time into the contiguous storage. - int numServices = m_serviceUUIDs.size(); - if (numServices > 0) { - m_advData.service_uuid_len = 16*numServices; - m_advData.p_service_uuid = new uint8_t[m_advData.service_uuid_len]; - uint8_t* p = m_advData.p_service_uuid; - for (int i=0; iuuid.uuid128, 16); - p+=16; - } - } else { - m_advData.service_uuid_len = 0; - ESP_LOGD(LOG_TAG, "- no services advertised"); - } - - esp_err_t errRc; - - if (m_customAdvData == false) { - // Set the configuration for advertising. - m_advData.set_scan_rsp = false; - errRc = ::esp_ble_gap_config_adv_data(&m_advData); - if (errRc != ESP_OK) { - ESP_LOGE(LOG_TAG, "<< esp_ble_gap_config_adv_data: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return; - } - } - - if (m_customScanResponseData == false) { - m_advData.set_scan_rsp = true; - errRc = ::esp_ble_gap_config_adv_data(&m_advData); - if (errRc != ESP_OK) { - ESP_LOGE(LOG_TAG, "<< esp_ble_gap_config_adv_data (Scan response): rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return; - } - } - - // If we had services to advertise then we previously allocated some storage for them. - // Here we release that storage. - if (m_advData.service_uuid_len > 0) { - delete[] m_advData.p_service_uuid; - m_advData.p_service_uuid = nullptr; - } - - // Start advertising. - errRc = ::esp_ble_gap_start_advertising(&m_advParams); - if (errRc != ESP_OK) { - ESP_LOGE(LOG_TAG, "<< esp_ble_gap_start_advertising: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return; - } - ESP_LOGD(LOG_TAG, "<< start"); -} // start - - -/** - * @brief Stop advertising. - * Stop advertising. - * @return N/A. - */ -void BLEAdvertising::stop() { - ESP_LOGD(LOG_TAG, ">> stop"); - esp_err_t errRc = ::esp_ble_gap_stop_advertising(); - if (errRc != ESP_OK) { - ESP_LOGE(LOG_TAG, "esp_ble_gap_stop_advertising: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return; - } - ESP_LOGD(LOG_TAG, "<< stop"); -} // stop - -/** - * @brief Add data to the payload to be advertised. - * @param [in] data The data to be added to the payload. - */ -void BLEAdvertisementData::addData(std::string data) { - if ((m_payload.length() + data.length()) > ESP_BLE_ADV_DATA_LEN_MAX) { - return; - } - m_payload.append(data); -} // addData - - -/** - * @brief Set the appearance. - * @param [in] appearance The appearance code value. - * - * See also: - * https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.gap.appearance.xml - */ -void BLEAdvertisementData::setAppearance(uint16_t appearance) { - char cdata[2]; - cdata[0] = 3; - cdata[1] = ESP_BLE_AD_TYPE_APPEARANCE; // 0x19 - addData(std::string(cdata, 2) + std::string((char *)&appearance,2)); -} // setAppearance - - -/** - * @brief Set the complete services. - * @param [in] uuid The single service to advertise. - */ -void BLEAdvertisementData::setCompleteServices(BLEUUID uuid) { - char cdata[2]; - switch(uuid.bitSize()) { - case 16: { - // [Len] [0x02] [LL] [HH] - cdata[0] = 3; - cdata[1] = ESP_BLE_AD_TYPE_16SRV_CMPL; // 0x03 - addData(std::string(cdata, 2) + std::string((char *)&uuid.getNative()->uuid.uuid16,2)); - break; - } - - case 32: { - // [Len] [0x04] [LL] [LL] [HH] [HH] - cdata[0] = 5; - cdata[1] = ESP_BLE_AD_TYPE_32SRV_CMPL; // 0x05 - addData(std::string(cdata, 2) + std::string((char *)&uuid.getNative()->uuid.uuid32,4)); - break; - } - - case 128: { - // [Len] [0x04] [0] [1] ... [15] - cdata[0] = 17; - cdata[1] = ESP_BLE_AD_TYPE_128SRV_CMPL; // 0x07 - addData(std::string(cdata, 2) + std::string((char *)uuid.getNative()->uuid.uuid128,16)); - break; - } - - default: - return; - } -} // setCompleteServices - - -/** - * @brief Set the advertisement flags. - * @param [in] The flags to be set in the advertisement. - * - * * ESP_BLE_ADV_FLAG_LIMIT_DISC - * * ESP_BLE_ADV_FLAG_GEN_DISC - * * ESP_BLE_ADV_FLAG_BREDR_NOT_SPT - * * ESP_BLE_ADV_FLAG_DMT_CONTROLLER_SPT - * * ESP_BLE_ADV_FLAG_DMT_HOST_SPT - * * ESP_BLE_ADV_FLAG_NON_LIMIT_DISC - */ -void BLEAdvertisementData::setFlags(uint8_t flag) { - char cdata[3]; - cdata[0] = 2; - cdata[1] = ESP_BLE_AD_TYPE_FLAG; // 0x01 - cdata[2] = flag; - addData(std::string(cdata, 3)); -} // setFlag - - - -/** - * @brief Set manufacturer specific data. - * @param [in] data Manufacturer data. - */ -void BLEAdvertisementData::setManufacturerData(std::string data) { - ESP_LOGD("BLEAdvertisementData", ">> setManufacturerData"); - char cdata[2]; - cdata[0] = data.length() + 1; - cdata[1] = ESP_BLE_AD_MANUFACTURER_SPECIFIC_TYPE; // 0xff - addData(std::string(cdata, 2) + data); - ESP_LOGD("BLEAdvertisementData", "<< setManufacturerData"); -} // setManufacturerData - - -/** - * @brief Set the name. - * @param [in] The complete name of the device. - */ -void BLEAdvertisementData::setName(std::string name) { - ESP_LOGD("BLEAdvertisementData", ">> setName: %s", name.c_str()); - char cdata[2]; - cdata[0] = name.length() + 1; - cdata[1] = ESP_BLE_AD_TYPE_NAME_CMPL; // 0x09 - addData(std::string(cdata, 2) + name); - ESP_LOGD("BLEAdvertisementData", "<< setName"); -} // setName - - -/** - * @brief Set the partial services. - * @param [in] uuid The single service to advertise. - */ -void BLEAdvertisementData::setPartialServices(BLEUUID uuid) { - char cdata[2]; - switch(uuid.bitSize()) { - case 16: { - // [Len] [0x02] [LL] [HH] - cdata[0] = 3; - cdata[1] = ESP_BLE_AD_TYPE_16SRV_PART; // 0x02 - addData(std::string(cdata, 2) + std::string((char *)&uuid.getNative()->uuid.uuid16,2)); - break; - } - - case 32: { - // [Len] [0x04] [LL] [LL] [HH] [HH] - cdata[0] = 5; - cdata[1] = ESP_BLE_AD_TYPE_32SRV_PART; // 0x04 - addData(std::string(cdata, 2) + std::string((char *)&uuid.getNative()->uuid.uuid32,4)); - break; - } - - case 128: { - // [Len] [0x04] [0] [1] ... [15] - cdata[0] = 17; - cdata[1] = ESP_BLE_AD_TYPE_128SRV_PART; // 0x06 - addData(std::string(cdata, 2) + std::string((char *)uuid.getNative()->uuid.uuid128,16)); - break; - } - - default: - return; - } -} // setPartialServices - - -/** - * @brief Set the service data (UUID + data) - * @param [in] uuid The UUID to set with the service data. Size of UUID will be used. - * @param [in] data The data to be associated with the service data advert. - */ -void BLEAdvertisementData::setServiceData(BLEUUID uuid, std::string data) { - char cdata[2]; - switch(uuid.bitSize()) { - case 16: { - // [Len] [0x16] [UUID16] data - cdata[0] = data.length() + 3; - cdata[1] = ESP_BLE_AD_TYPE_SERVICE_DATA; // 0x16 - addData(std::string(cdata, 2) + std::string((char *)&uuid.getNative()->uuid.uuid16,2) + data); - break; - } - - case 32: { - // [Len] [0x20] [UUID32] data - cdata[0] = data.length() + 5; - cdata[1] = ESP_BLE_AD_TYPE_32SERVICE_DATA; // 0x20 - addData(std::string(cdata, 2) + std::string((char *)&uuid.getNative()->uuid.uuid32,4) + data); - break; - } - - case 128: { - // [Len] [0x21] [UUID128] data - cdata[0] = data.length() + 17; - cdata[1] = ESP_BLE_AD_TYPE_128SERVICE_DATA; // 0x21 - addData(std::string(cdata, 2) + std::string((char *)uuid.getNative()->uuid.uuid128,16) + data); - break; - } - - default: - return; - } -} // setServiceData - - -/** - * @brief Set the short name. - * @param [in] The short name of the device. - */ -void BLEAdvertisementData::setShortName(std::string name) { - ESP_LOGD("BLEAdvertisementData", ">> setShortName: %s", name.c_str()); - char cdata[2]; - cdata[0] = name.length() + 1; - cdata[1] = ESP_BLE_AD_TYPE_NAME_SHORT; // 0x08 - addData(std::string(cdata, 2) + name); - ESP_LOGD("BLEAdvertisementData", "<< setShortName"); -} // setShortName - - - -/** - * @brief Retrieve the payload that is to be advertised. - * @return The payload that is to be advertised. - */ -std::string BLEAdvertisementData::getPayload() { - return m_payload; -} // getPayload - - -#endif /* CONFIG_BT_ENABLED */ diff --git a/lib/ESP32_BLE_Arduino/src/BLEAdvertising.h b/lib/ESP32_BLE_Arduino/src/BLEAdvertising.h deleted file mode 100644 index e3165298..00000000 --- a/lib/ESP32_BLE_Arduino/src/BLEAdvertising.h +++ /dev/null @@ -1,68 +0,0 @@ -/* - * BLEAdvertising.h - * - * Created on: Jun 21, 2017 - * Author: kolban - */ - -#ifndef COMPONENTS_CPP_UTILS_BLEADVERTISING_H_ -#define COMPONENTS_CPP_UTILS_BLEADVERTISING_H_ -#include "sdkconfig.h" -#if defined(CONFIG_BT_ENABLED) -#include -#include "BLEUUID.h" -#include - -/** - * @brief Advertisement data set by the programmer to be published by the %BLE server. - */ -class BLEAdvertisementData { - // Only a subset of the possible BLE architected advertisement fields are currently exposed. Others will - // be exposed on demand/request or as time permits. - // -public: - void setAppearance(uint16_t appearance); - void setCompleteServices(BLEUUID uuid); - void setFlags(uint8_t); - void setManufacturerData(std::string data); - void setName(std::string name); - void setPartialServices(BLEUUID uuid); - void setServiceData(BLEUUID uuid, std::string data); - void setShortName(std::string name); - void addData(std::string data); // Add data to the payload. - std::string getPayload(); // Retrieve the current advert payload. - -private: - friend class BLEAdvertising; - std::string m_payload; // The payload of the advertisement. -}; // BLEAdvertisementData - - -/** - * @brief Perform and manage %BLE advertising. - * - * A %BLE server will want to perform advertising in order to make itself known to %BLE clients. - */ -class BLEAdvertising { -public: - BLEAdvertising(); - void addServiceUUID(BLEUUID serviceUUID); - void addServiceUUID(const char* serviceUUID); - void start(); - void stop(); - void setAppearance(uint16_t appearance); - void setMaxInterval(uint16_t maxinterval); - void setMinInterval(uint16_t mininterval); - void setAdvertisementData(BLEAdvertisementData& advertisementData); - void setScanFilter(bool scanRequertWhitelistOnly, bool connectWhitelistOnly); - void setScanResponseData(BLEAdvertisementData& advertisementData); - -private: - esp_ble_adv_data_t m_advData; - esp_ble_adv_params_t m_advParams; - std::vector m_serviceUUIDs; - bool m_customAdvData; // Are we using custom advertising data? - bool m_customScanResponseData; // Are we using custom scan response data? -}; -#endif /* CONFIG_BT_ENABLED */ -#endif /* COMPONENTS_CPP_UTILS_BLEADVERTISING_H_ */ diff --git a/lib/ESP32_BLE_Arduino/src/BLEBeacon.cpp b/lib/ESP32_BLE_Arduino/src/BLEBeacon.cpp deleted file mode 100644 index a63197ca..00000000 --- a/lib/ESP32_BLE_Arduino/src/BLEBeacon.cpp +++ /dev/null @@ -1,84 +0,0 @@ -/* - * BLEBeacon.cpp - * - * Created on: Jan 4, 2018 - * Author: kolban - */ -#include "sdkconfig.h" -#if defined(CONFIG_BT_ENABLED) -#include -#include -#include "BLEBeacon.h" - -#define ENDIAN_CHANGE_U16(x) ((((x)&0xFF00)>>8) + (((x)&0xFF)<<8)) - -static const char LOG_TAG[] = "BLEBeacon"; - -BLEBeacon::BLEBeacon() { - m_beaconData.manufacturerId = 0x4c00; - m_beaconData.subType = 0x02; - m_beaconData.subTypeLength = 0x15; - m_beaconData.major = 0; - m_beaconData.minor = 0; - m_beaconData.signalPower = 0; - memset(m_beaconData.proximityUUID, 0, sizeof(m_beaconData.proximityUUID)); -} // BLEBeacon - -std::string BLEBeacon::getData() { - return std::string((char*)&m_beaconData, sizeof(m_beaconData)); -} // getData - -uint16_t BLEBeacon::getMajor() { - return m_beaconData.major; -} - -uint16_t BLEBeacon::getManufacturerId() { - return m_beaconData.manufacturerId; -} - -uint16_t BLEBeacon::getMinor() { - return m_beaconData.minor; -} - -BLEUUID BLEBeacon::getProximityUUID() { - return BLEUUID(m_beaconData.proximityUUID, 16, false); -} - -int8_t BLEBeacon::getSignalPower() { - return m_beaconData.signalPower; -} - -/** - * Set the raw data for the beacon record. - */ -void BLEBeacon::setData(std::string data) { - if (data.length() != sizeof(m_beaconData)) { - ESP_LOGE(LOG_TAG, "Unable to set the data ... length passed in was %d and expected %d", data.length(), sizeof(m_beaconData)); - return; - } - memcpy(&m_beaconData, data.data(), sizeof(m_beaconData)); -} // setData - -void BLEBeacon::setMajor(uint16_t major) { - m_beaconData.major = ENDIAN_CHANGE_U16(major); -} // setMajor - -void BLEBeacon::setManufacturerId(uint16_t manufacturerId) { - m_beaconData.manufacturerId = ENDIAN_CHANGE_U16(manufacturerId); -} // setManufacturerId - -void BLEBeacon::setMinor(uint16_t minor) { - m_beaconData.minor = ENDIAN_CHANGE_U16(minor); -} // setMinior - -void BLEBeacon::setProximityUUID(BLEUUID uuid) { - uuid = uuid.to128(); - memcpy(m_beaconData.proximityUUID, uuid.getNative()->uuid.uuid128, 16); -} // setProximityUUID - -void BLEBeacon::setSignalPower(int8_t signalPower) { - m_beaconData.signalPower = signalPower; -} // setSignalPower - - -#endif diff --git a/lib/ESP32_BLE_Arduino/src/BLEBeacon.h b/lib/ESP32_BLE_Arduino/src/BLEBeacon.h deleted file mode 100644 index 0b02e2bd..00000000 --- a/lib/ESP32_BLE_Arduino/src/BLEBeacon.h +++ /dev/null @@ -1,43 +0,0 @@ -/* - * BLEBeacon2.h - * - * Created on: Jan 4, 2018 - * Author: kolban - */ - -#ifndef COMPONENTS_CPP_UTILS_BLEBEACON_H_ -#define COMPONENTS_CPP_UTILS_BLEBEACON_H_ -#include "BLEUUID.h" -/** - * @brief Representation of a beacon. - * See: - * * https://en.wikipedia.org/wiki/IBeacon - */ -class BLEBeacon { -private: - struct { - uint16_t manufacturerId; - uint8_t subType; - uint8_t subTypeLength; - uint8_t proximityUUID[16]; - uint16_t major; - uint16_t minor; - int8_t signalPower; - } __attribute__((packed))m_beaconData; -public: - BLEBeacon(); - std::string getData(); - uint16_t getMajor(); - uint16_t getMinor(); - uint16_t getManufacturerId(); - BLEUUID getProximityUUID(); - int8_t getSignalPower(); - void setData(std::string data); - void setMajor(uint16_t major); - void setMinor(uint16_t minor); - void setManufacturerId(uint16_t manufacturerId); - void setProximityUUID(BLEUUID uuid); - void setSignalPower(int8_t signalPower); -}; // BLEBeacon - -#endif /* COMPONENTS_CPP_UTILS_BLEBEACON_H_ */ diff --git a/lib/ESP32_BLE_Arduino/src/BLECharacteristic.cpp b/lib/ESP32_BLE_Arduino/src/BLECharacteristic.cpp deleted file mode 100644 index 931c753d..00000000 --- a/lib/ESP32_BLE_Arduino/src/BLECharacteristic.cpp +++ /dev/null @@ -1,793 +0,0 @@ -/* - * BLECharacteristic.cpp - * - * Created on: Jun 22, 2017 - * Author: kolban - */ -#include "sdkconfig.h" -#if defined(CONFIG_BT_ENABLED) -#include -#include -#include -#include -#include "sdkconfig.h" -#include -#include -#include "BLECharacteristic.h" -#include "BLEService.h" -#include "BLEDevice.h" -#include "BLEUtils.h" -#include "BLE2902.h" -#include "GeneralUtils.h" -#ifdef ARDUINO_ARCH_ESP32 -#include "esp32-hal-log.h" -#endif - -static const char* LOG_TAG = "BLECharacteristic"; - -#define NULL_HANDLE (0xffff) - - -/** - * @brief Construct a characteristic - * @param [in] uuid - UUID (const char*) for the characteristic. - * @param [in] properties - Properties for the characteristic. - */ -BLECharacteristic::BLECharacteristic(const char* uuid, uint32_t properties) : BLECharacteristic(BLEUUID(uuid), properties) { -} - -/** - * @brief Construct a characteristic - * @param [in] uuid - UUID for the characteristic. - * @param [in] properties - Properties for the characteristic. - */ -BLECharacteristic::BLECharacteristic(BLEUUID uuid, uint32_t properties) { - m_bleUUID = uuid; - m_handle = NULL_HANDLE; - m_properties = (esp_gatt_char_prop_t)0; - m_pCallbacks = nullptr; - - setBroadcastProperty((properties & PROPERTY_BROADCAST) !=0); - setReadProperty((properties & PROPERTY_READ) !=0); - setWriteProperty((properties & PROPERTY_WRITE) !=0); - setNotifyProperty((properties & PROPERTY_NOTIFY) !=0); - setIndicateProperty((properties & PROPERTY_INDICATE) !=0); - setWriteNoResponseProperty((properties & PROPERTY_WRITE_NR) !=0); -} // BLECharacteristic - -/** - * @brief Destructor. - */ -BLECharacteristic::~BLECharacteristic() { - //free(m_value.attr_value); // Release the storage for the value. -} // ~BLECharacteristic - - -/** - * @brief Associate a descriptor with this characteristic. - * @param [in] pDescriptor - * @return N/A. - */ -void BLECharacteristic::addDescriptor(BLEDescriptor* pDescriptor) { - ESP_LOGD(LOG_TAG, ">> addDescriptor(): Adding %s to %s", pDescriptor->toString().c_str(), toString().c_str()); - m_descriptorMap.setByUUID(pDescriptor->getUUID(), pDescriptor); - ESP_LOGD(LOG_TAG, "<< addDescriptor()"); -} // addDescriptor - - -/** - * @brief Register a new characteristic with the ESP runtime. - * @param [in] pService The service with which to associate this characteristic. - */ -void BLECharacteristic::executeCreate(BLEService* pService) { - ESP_LOGD(LOG_TAG, ">> executeCreate()"); - - if (m_handle != NULL_HANDLE) { - ESP_LOGE(LOG_TAG, "Characteristic already has a handle."); - return; - } - - m_pService = pService; // Save the service for to which this characteristic belongs. - - ESP_LOGD(LOG_TAG, "Registering characteristic (esp_ble_gatts_add_char): uuid: %s, service: %s", - getUUID().toString().c_str(), - m_pService->toString().c_str()); - - esp_attr_control_t control; - control.auto_rsp = ESP_GATT_RSP_BY_APP; - - m_semaphoreCreateEvt.take("executeCreate"); - - /* - esp_attr_value_t value; - value.attr_len = m_value.getLength(); - value.attr_max_len = ESP_GATT_MAX_ATTR_LEN; - value.attr_value = m_value.getData(); - */ - - esp_err_t errRc = ::esp_ble_gatts_add_char( - m_pService->getHandle(), - getUUID().getNative(), - static_cast(m_permissions), - getProperties(), - //&value, - nullptr, - &control); // Whether to auto respond or not. - - if (errRc != ESP_OK) { - ESP_LOGE(LOG_TAG, "<< esp_ble_gatts_add_char: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return; - } - - m_semaphoreCreateEvt.wait("executeCreate"); - - // Now that we have registered the characteristic, we must also register all the descriptors associated with this - // characteristic. We iterate through each of those and invoke the registration call to register them with the - // ESP environment. - - BLEDescriptor* pDescriptor = m_descriptorMap.getFirst(); - - while (pDescriptor != nullptr) { - pDescriptor->executeCreate(this); - pDescriptor = m_descriptorMap.getNext(); - } // End while - - ESP_LOGD(LOG_TAG, "<< executeCreate"); -} // executeCreate - - -/** - * @brief Return the BLE Descriptor for the given UUID if associated with this characteristic. - * @param [in] descriptorUUID The UUID of the descriptor that we wish to retrieve. - * @return The BLE Descriptor. If no such descriptor is associated with the characteristic, nullptr is returned. - */ -BLEDescriptor* BLECharacteristic::getDescriptorByUUID(const char* descriptorUUID) { - return m_descriptorMap.getByUUID(BLEUUID(descriptorUUID)); -} // getDescriptorByUUID - - -/** - * @brief Return the BLE Descriptor for the given UUID if associated with this characteristic. - * @param [in] descriptorUUID The UUID of the descriptor that we wish to retrieve. - * @return The BLE Descriptor. If no such descriptor is associated with the characteristic, nullptr is returned. - */ -BLEDescriptor* BLECharacteristic::getDescriptorByUUID(BLEUUID descriptorUUID) { - return m_descriptorMap.getByUUID(descriptorUUID); -} // getDescriptorByUUID - - -/** - * @brief Get the handle of the characteristic. - * @return The handle of the characteristic. - */ -uint16_t BLECharacteristic::getHandle() { - return m_handle; -} // getHandle - -void BLECharacteristic::setAccessPermissions(esp_gatt_perm_t perm) { - m_permissions = perm; -} - -esp_gatt_char_prop_t BLECharacteristic::getProperties() { - return m_properties; -} // getProperties - - -/** - * @brief Get the service associated with this characteristic. - */ -BLEService* BLECharacteristic::getService() { - return m_pService; -} // getService - - -/** - * @brief Get the UUID of the characteristic. - * @return The UUID of the characteristic. - */ -BLEUUID BLECharacteristic::getUUID() { - return m_bleUUID; -} // getUUID - - -/** - * @brief Retrieve the current value of the characteristic. - * @return A pointer to storage containing the current characteristic value. - */ -std::string BLECharacteristic::getValue() { - return m_value.getValue(); -} // getValue - - -/** - * Handle a GATT server event. - */ -void BLECharacteristic::handleGATTServerEvent( - esp_gatts_cb_event_t event, - esp_gatt_if_t gatts_if, - esp_ble_gatts_cb_param_t* param) { - ESP_LOGD(LOG_TAG, ">> handleGATTServerEvent: %s", BLEUtils::gattServerEventTypeToString(event).c_str()); - - switch(event) { - // Events handled: - // - // ESP_GATTS_ADD_CHAR_EVT - // ESP_GATTS_CONF_EVT - // ESP_GATTS_CONNECT_EVT - // ESP_GATTS_DISCONNECT_EVT - // ESP_GATTS_EXEC_WRITE_EVT - // ESP_GATTS_READ_EVT - // ESP_GATTS_WRITE_EVT - - // - // ESP_GATTS_EXEC_WRITE_EVT - // When we receive this event it is an indication that a previous write long needs to be committed. - // - // exec_write: - // - uint16_t conn_id - // - uint32_t trans_id - // - esp_bd_addr_t bda - // - uint8_t exec_write_flag - Either ESP_GATT_PREP_WRITE_EXEC or ESP_GATT_PREP_WRITE_CANCEL - // - case ESP_GATTS_EXEC_WRITE_EVT: { - if (param->exec_write.exec_write_flag == ESP_GATT_PREP_WRITE_EXEC) { - m_value.commit(); - if (m_pCallbacks != nullptr) { - m_pCallbacks->onWrite(this); // Invoke the onWrite callback handler. - } - } else { - m_value.cancel(); - } - - esp_err_t errRc = ::esp_ble_gatts_send_response( - gatts_if, - param->write.conn_id, - param->write.trans_id, ESP_GATT_OK, nullptr); - if (errRc != ESP_OK) { - ESP_LOGE(LOG_TAG, "esp_ble_gatts_send_response: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - } - break; - } // ESP_GATTS_EXEC_WRITE_EVT - - - // ESP_GATTS_ADD_CHAR_EVT - Indicate that a characteristic was added to the service. - // add_char: - // - esp_gatt_status_t status - // - uint16_t attr_handle - // - uint16_t service_handle - // - esp_bt_uuid_t char_uuid - case ESP_GATTS_ADD_CHAR_EVT: { - if (getUUID().equals(BLEUUID(param->add_char.char_uuid)) && - getHandle() == param->add_char.attr_handle && - getService()->getHandle()==param->add_char.service_handle) { - m_semaphoreCreateEvt.give(); - } - break; - } // ESP_GATTS_ADD_CHAR_EVT - - - // ESP_GATTS_WRITE_EVT - A request to write the value of a characteristic has arrived. - // - // write: - // - uint16_t conn_id - // - uint16_t trans_id - // - esp_bd_addr_t bda - // - uint16_t handle - // - uint16_t offset - // - bool need_rsp - // - bool is_prep - // - uint16_t len - // - uint8_t *value - // - case ESP_GATTS_WRITE_EVT: { -// We check if this write request is for us by comparing the handles in the event. If it is for us -// we save the new value. Next we look at the need_rsp flag which indicates whether or not we need -// to send a response. If we do, then we formulate a response and send it. - if (param->write.handle == m_handle) { - if (param->write.is_prep) { - m_value.addPart(param->write.value, param->write.len); - } else { - setValue(param->write.value, param->write.len); - } - - ESP_LOGD(LOG_TAG, " - Response to write event: New value: handle: %.2x, uuid: %s", - getHandle(), getUUID().toString().c_str()); - - char* pHexData = BLEUtils::buildHexData(nullptr, param->write.value, param->write.len); - ESP_LOGD(LOG_TAG, " - Data: length: %d, data: %s", param->write.len, pHexData); - free(pHexData); - - if (param->write.need_rsp) { - esp_gatt_rsp_t rsp; - - rsp.attr_value.len = param->write.len; - rsp.attr_value.handle = m_handle; - rsp.attr_value.offset = param->write.offset; - rsp.attr_value.auth_req = ESP_GATT_AUTH_REQ_NONE; - memcpy(rsp.attr_value.value, param->write.value, param->write.len); - - esp_err_t errRc = ::esp_ble_gatts_send_response( - gatts_if, - param->write.conn_id, - param->write.trans_id, ESP_GATT_OK, &rsp); - if (errRc != ESP_OK) { - ESP_LOGE(LOG_TAG, "esp_ble_gatts_send_response: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - } - } // Response needed - - if (m_pCallbacks != nullptr && param->write.is_prep != true) { - m_pCallbacks->onWrite(this); // Invoke the onWrite callback handler. - } - } // Match on handles. - break; - } // ESP_GATTS_WRITE_EVT - - - // ESP_GATTS_READ_EVT - A request to read the value of a characteristic has arrived. - // - // read: - // - uint16_t conn_id - // - uint32_t trans_id - // - esp_bd_addr_t bda - // - uint16_t handle - // - uint16_t offset - // - bool is_long - // - bool need_rsp - // - case ESP_GATTS_READ_EVT: { - if (param->read.handle == m_handle) { - - - -// Here's an interesting thing. The read request has the option of saying whether we need a response -// or not. What would it "mean" to receive a read request and NOT send a response back? That feels like -// a very strange read. -// -// We have to handle the case where the data we wish to send back to the client is greater than the maximum -// packet size of 22 bytes. In this case, we become responsible for chunking the data into units of 22 bytes. -// The apparent algorithm is as follows: -// -// If the is_long flag is set then this is a follow on from an original read and we will already have sent at least 22 bytes. -// If the is_long flag is not set then we need to check how much data we are going to send. If we are sending LESS than -// 22 bytes, then we "just" send it and thats the end of the story. -// If we are sending 22 bytes exactly, we just send it BUT we will get a follow on request. -// If we are sending more than 22 bytes, we send the first 22 bytes and we will get a follow on request. -// Because of follow on request processing, we need to maintain an offset of how much data we have already sent -// so that when a follow on request arrives, we know where to start in the data to send the next sequence. -// Note that the indication that the client will send a follow on request is that we sent exactly 22 bytes as a response. -// If our payload is divisible by 22 then the last response will be a response of 0 bytes in length. -// -// The following code has deliberately not been factored to make it fewer statements because this would cloud the -// the logic flow comprehension. -// - // TODO requires some more research to confirm that 512 is max PDU like in bluetooth specs - uint16_t maxOffset = BLEDevice::getMTU() - 1; - if (BLEDevice::getMTU() > 512) { - maxOffset = 512; - } - if (param->read.need_rsp) { - ESP_LOGD(LOG_TAG, "Sending a response (esp_ble_gatts_send_response)"); - esp_gatt_rsp_t rsp; - - if (param->read.is_long) { - std::string value = m_value.getValue(); - - if (value.length() - m_value.getReadOffset() < maxOffset) { - // This is the last in the chain - rsp.attr_value.len = value.length() - m_value.getReadOffset(); - rsp.attr_value.offset = m_value.getReadOffset(); - memcpy(rsp.attr_value.value, value.data() + rsp.attr_value.offset, rsp.attr_value.len); - m_value.setReadOffset(0); - } else { - // There will be more to come. - rsp.attr_value.len = maxOffset; - rsp.attr_value.offset = m_value.getReadOffset(); - memcpy(rsp.attr_value.value, value.data() + rsp.attr_value.offset, rsp.attr_value.len); - m_value.setReadOffset(rsp.attr_value.offset + maxOffset); - } - } else { // read.is_long == false - - if (m_pCallbacks != nullptr) { // If is.long is false then this is the first (or only) request to read data, so invoke the callback - m_pCallbacks->onRead(this); // Invoke the read callback. - } - - std::string value = m_value.getValue(); - - if (value.length()+1 > maxOffset) { - // Too big for a single shot entry. - m_value.setReadOffset(maxOffset); - rsp.attr_value.len = maxOffset; - rsp.attr_value.offset = 0; - memcpy(rsp.attr_value.value, value.data(), rsp.attr_value.len); - } else { - // Will fit in a single packet with no callbacks required. - rsp.attr_value.len = value.length(); - rsp.attr_value.offset = 0; - memcpy(rsp.attr_value.value, value.data(), rsp.attr_value.len); - } - } - rsp.attr_value.handle = param->read.handle; - rsp.attr_value.auth_req = ESP_GATT_AUTH_REQ_NONE; - - char *pHexData = BLEUtils::buildHexData(nullptr, rsp.attr_value.value, rsp.attr_value.len); - ESP_LOGD(LOG_TAG, " - Data: length=%d, data=%s, offset=%d", rsp.attr_value.len, pHexData, rsp.attr_value.offset); - free(pHexData); - - esp_err_t errRc = ::esp_ble_gatts_send_response( - gatts_if, param->read.conn_id, - param->read.trans_id, - ESP_GATT_OK, - &rsp); - if (errRc != ESP_OK) { - ESP_LOGE(LOG_TAG, "esp_ble_gatts_send_response: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - } - } // Response needed - } // Handle matches this characteristic. - break; - } // ESP_GATTS_READ_EVT - - - // ESP_GATTS_CONF_EVT - // - // conf: - // - esp_gatt_status_t status – The status code. - // - uint16_t conn_id – The connection used. - // - case ESP_GATTS_CONF_EVT: { - m_semaphoreConfEvt.give(); - break; - } - - case ESP_GATTS_CONNECT_EVT: { - m_semaphoreConfEvt.give(); - break; - } - - case ESP_GATTS_DISCONNECT_EVT: { - m_semaphoreConfEvt.give(); - break; - } - - default: { - break; - } // default - - } // switch event - - // Give each of the descriptors associated with this characteristic the opportunity to handle the - // event. - - m_descriptorMap.handleGATTServerEvent(event, gatts_if, param); - ESP_LOGD(LOG_TAG, "<< handleGATTServerEvent"); -} // handleGATTServerEvent - - -/** - * @brief Send an indication. - * An indication is a transmission of up to the first 20 bytes of the characteristic value. An indication - * will block waiting a positive confirmation from the client. - * @return N/A - */ -void BLECharacteristic::indicate() { - - ESP_LOGD(LOG_TAG, ">> indicate: length: %d", m_value.getValue().length()); - - assert(getService() != nullptr); - assert(getService()->getServer() != nullptr); - - GeneralUtils::hexDump((uint8_t*)m_value.getValue().data(), m_value.getValue().length()); - - if (getService()->getServer()->getConnectedCount() == 0) { - ESP_LOGD(LOG_TAG, "<< indicate: No connected clients."); - return; - } - - // Test to see if we have a 0x2902 descriptor. If we do, then check to see if indications are enabled - // and, if not, prevent the indication. - - BLE2902 *p2902 = (BLE2902*)getDescriptorByUUID((uint16_t)0x2902); - if (p2902 != nullptr && !p2902->getIndications()) { - ESP_LOGD(LOG_TAG, "<< indications disabled; ignoring"); - return; - } - - if (m_value.getValue().length() > (BLEDevice::getMTU() - 3)) { - ESP_LOGI(LOG_TAG, "- Truncating to %d bytes (maximum indicate size)", BLEDevice::getMTU() - 3); - } - - size_t length = m_value.getValue().length(); - - m_semaphoreConfEvt.take("indicate"); - - esp_err_t errRc = ::esp_ble_gatts_send_indicate( - getService()->getServer()->getGattsIf(), - getService()->getServer()->getConnId(), - getHandle(), length, (uint8_t*)m_value.getValue().data(), true); // The need_confirm = true makes this an indication. - - if (errRc != ESP_OK) { - ESP_LOGE(LOG_TAG, "<< esp_ble_gatts_send_indicate: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return; - } - - m_semaphoreConfEvt.wait("indicate"); - ESP_LOGD(LOG_TAG, "<< indicate"); -} // indicate - - -/** - * @brief Send a notify. - * A notification is a transmission of up to the first 20 bytes of the characteristic value. An notification - * will not block; it is a fire and forget. - * @return N/A. - */ -void BLECharacteristic::notify() { - ESP_LOGD(LOG_TAG, ">> notify: length: %d", m_value.getValue().length()); - - - assert(getService() != nullptr); - assert(getService()->getServer() != nullptr); - - - GeneralUtils::hexDump((uint8_t*)m_value.getValue().data(), m_value.getValue().length()); - - if (getService()->getServer()->getConnectedCount() == 0) { - ESP_LOGD(LOG_TAG, "<< notify: No connected clients."); - return; - } - - // Test to see if we have a 0x2902 descriptor. If we do, then check to see if notification is enabled - // and, if not, prevent the notification. - - BLE2902 *p2902 = (BLE2902*)getDescriptorByUUID((uint16_t)0x2902); - if (p2902 != nullptr && !p2902->getNotifications()) { - ESP_LOGD(LOG_TAG, "<< notifications disabled; ignoring"); - return; - } - - if (m_value.getValue().length() > (BLEDevice::getMTU() - 3)) { - ESP_LOGI(LOG_TAG, "- Truncating to %d bytes (maximum notify size)", BLEDevice::getMTU() - 3); - } - - size_t length = m_value.getValue().length(); - - m_semaphoreConfEvt.take("notify"); - - esp_err_t errRc = ::esp_ble_gatts_send_indicate( - getService()->getServer()->getGattsIf(), - getService()->getServer()->getConnId(), - getHandle(), length, (uint8_t*)m_value.getValue().data(), false); // The need_confirm = false makes this a notify. - if (errRc != ESP_OK) { - ESP_LOGE(LOG_TAG, "<< esp_ble_gatts_send_indicate: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return; - } - - m_semaphoreConfEvt.wait("notify"); - - ESP_LOGD(LOG_TAG, "<< notify"); -} // Notify - - -/** - * @brief Set the permission to broadcast. - * A characteristics has properties associated with it which define what it is capable of doing. - * One of these is the broadcast flag. - * @param [in] value The flag value of the property. - * @return N/A - */ -void BLECharacteristic::setBroadcastProperty(bool value) { - //ESP_LOGD(LOG_TAG, "setBroadcastProperty(%d)", value); - if (value) { - m_properties = (esp_gatt_char_prop_t)(m_properties | ESP_GATT_CHAR_PROP_BIT_BROADCAST); - } else { - m_properties = (esp_gatt_char_prop_t)(m_properties & ~ESP_GATT_CHAR_PROP_BIT_BROADCAST); - } -} // setBroadcastProperty - - -/** - * @brief Set the callback handlers for this characteristic. - * @param [in] pCallbacks An instance of a callbacks structure used to define any callbacks for the characteristic. - */ -void BLECharacteristic::setCallbacks(BLECharacteristicCallbacks* pCallbacks) { - ESP_LOGD(LOG_TAG, ">> setCallbacks: 0x%x", (uint32_t)pCallbacks); - m_pCallbacks = pCallbacks; - ESP_LOGD(LOG_TAG, "<< setCallbacks"); -} // setCallbacks - - -/** - * @brief Set the BLE handle associated with this characteristic. - * A user program will request that a characteristic be created against a service. When the characteristic has been - * registered, the service will be given a "handle" that it knows the characteristic as. This handle is unique to the - * server/service but it is told to the service, not the characteristic associated with the service. This internally - * exposed function can be invoked by the service against this model of the characteristic to allow the characteristic - * to learn its own handle. Once the characteristic knows its own handle, it will be able to see incoming GATT events - * that will be propagated down to it which contain a handle value and now know that the event is destined for it. - * @param [in] handle The handle associated with this characteristic. - */ -void BLECharacteristic::setHandle(uint16_t handle) { - ESP_LOGD(LOG_TAG, ">> setHandle: handle=0x%.2x, characteristic uuid=%s", handle, getUUID().toString().c_str()); - m_handle = handle; - ESP_LOGD(LOG_TAG, "<< setHandle"); -} // setHandle - - -/** - * @brief Set the Indicate property value. - * @param [in] value Set to true if we are to allow indicate messages. - */ -void BLECharacteristic::setIndicateProperty(bool value) { - //ESP_LOGD(LOG_TAG, "setIndicateProperty(%d)", value); - if (value) { - m_properties = (esp_gatt_char_prop_t)(m_properties | ESP_GATT_CHAR_PROP_BIT_INDICATE); - } else { - m_properties = (esp_gatt_char_prop_t)(m_properties & ~ESP_GATT_CHAR_PROP_BIT_INDICATE); - } -} // setIndicateProperty - - -/** - * @brief Set the Notify property value. - * @param [in] value Set to true if we are to allow notification messages. - */ -void BLECharacteristic::setNotifyProperty(bool value) { - //ESP_LOGD(LOG_TAG, "setNotifyProperty(%d)", value); - if (value) { - m_properties = (esp_gatt_char_prop_t)(m_properties | ESP_GATT_CHAR_PROP_BIT_NOTIFY); - } else { - m_properties = (esp_gatt_char_prop_t)(m_properties & ~ESP_GATT_CHAR_PROP_BIT_NOTIFY); - } -} // setNotifyProperty - - -/** - * @brief Set the Read property value. - * @param [in] value Set to true if we are to allow reads. - */ -void BLECharacteristic::setReadProperty(bool value) { - //ESP_LOGD(LOG_TAG, "setReadProperty(%d)", value); - if (value) { - m_properties = (esp_gatt_char_prop_t)(m_properties | ESP_GATT_CHAR_PROP_BIT_READ); - } else { - m_properties = (esp_gatt_char_prop_t)(m_properties & ~ESP_GATT_CHAR_PROP_BIT_READ); - } -} // setReadProperty - - -/** - * @brief Set the value of the characteristic. - * @param [in] data The data to set for the characteristic. - * @param [in] length The length of the data in bytes. - */ -void BLECharacteristic::setValue(uint8_t* data, size_t length) { - char *pHex = BLEUtils::buildHexData(nullptr, data, length); - ESP_LOGD(LOG_TAG, ">> setValue: length=%d, data=%s, characteristic UUID=%s", length, pHex, getUUID().toString().c_str()); - free(pHex); - if (length > ESP_GATT_MAX_ATTR_LEN) { - ESP_LOGE(LOG_TAG, "Size %d too large, must be no bigger than %d", length, ESP_GATT_MAX_ATTR_LEN); - return; - } - m_value.setValue(data, length); - ESP_LOGD(LOG_TAG, "<< setValue"); -} // setValue - - -/** - * @brief Set the value of the characteristic from string data. - * We set the value of the characteristic from the bytes contained in the - * string. - * @param [in] Set the value of the characteristic. - * @return N/A. - */ -void BLECharacteristic::setValue(std::string value) { - setValue((uint8_t*)(value.data()), value.length()); -} // setValue - -void BLECharacteristic::setValue(uint16_t& data16) { - uint8_t temp[2]; - temp[0]=data16; - temp[1]=data16>>8; - setValue(temp, 2); -} // setValue - -void BLECharacteristic::setValue(uint32_t& data32) { - uint8_t temp[4]; - temp[0]=data32; - temp[1]=data32>>8; - temp[2]=data32>>16; - temp[3]=data32>>24; - setValue(temp, 4); -} // setValue - -void BLECharacteristic::setValue(int& data32) { - uint8_t temp[4]; - temp[0]=data32; - temp[1]=data32>>8; - temp[2]=data32>>16; - temp[3]=data32>>24; - setValue(temp, 4); -} // setValue - -void BLECharacteristic::setValue(float& data32) { - uint8_t temp[4]; - *((float *)temp) = data32; - setValue(temp, 4); -} // setValue - -void BLECharacteristic::setValue(double& data64) { - uint8_t temp[8]; - *((double *)temp) = data64; - setValue(temp, 8); -} // setValue - - -/** - * @brief Set the Write No Response property value. - * @param [in] value Set to true if we are to allow writes with no response. - */ -void BLECharacteristic::setWriteNoResponseProperty(bool value) { - //ESP_LOGD(LOG_TAG, "setWriteNoResponseProperty(%d)", value); - if (value) { - m_properties = (esp_gatt_char_prop_t)(m_properties | ESP_GATT_CHAR_PROP_BIT_WRITE_NR); - } else { - m_properties = (esp_gatt_char_prop_t)(m_properties & ~ESP_GATT_CHAR_PROP_BIT_WRITE_NR); - } -} // setWriteNoResponseProperty - - -/** - * @brief Set the Write property value. - * @param [in] value Set to true if we are to allow writes. - */ -void BLECharacteristic::setWriteProperty(bool value) { - //ESP_LOGD(LOG_TAG, "setWriteProperty(%d)", value); - if (value) { - m_properties = (esp_gatt_char_prop_t)(m_properties | ESP_GATT_CHAR_PROP_BIT_WRITE); - } else { - m_properties = (esp_gatt_char_prop_t)(m_properties & ~ESP_GATT_CHAR_PROP_BIT_WRITE); - } -} // setWriteProperty - - -/** - * @brief Return a string representation of the characteristic. - * @return A string representation of the characteristic. - */ -std::string BLECharacteristic::toString() { - std::stringstream stringstream; - stringstream << std::hex << std::setfill('0'); - stringstream << "UUID: " << m_bleUUID.toString() + ", handle: 0x" << std::setw(2) << m_handle; - stringstream << " " << - ((m_properties & ESP_GATT_CHAR_PROP_BIT_READ)?"Read ":"") << - ((m_properties & ESP_GATT_CHAR_PROP_BIT_WRITE)?"Write ":"") << - ((m_properties & ESP_GATT_CHAR_PROP_BIT_WRITE_NR)?"WriteNoResponse ":"") << - ((m_properties & ESP_GATT_CHAR_PROP_BIT_BROADCAST)?"Broadcast ":"") << - ((m_properties & ESP_GATT_CHAR_PROP_BIT_NOTIFY)?"Notify ":"") << - ((m_properties & ESP_GATT_CHAR_PROP_BIT_INDICATE)?"Indicate ":""); - return stringstream.str(); -} // toString - - -BLECharacteristicCallbacks::~BLECharacteristicCallbacks() {} - - -/** - * @brief Callback function to support a read request. - * @param [in] pCharacteristic The characteristic that is the source of the event. - */ -void BLECharacteristicCallbacks::onRead(BLECharacteristic *pCharacteristic) { - ESP_LOGD("BLECharacteristicCallbacks", ">> onRead: default"); - ESP_LOGD("BLECharacteristicCallbacks", "<< onRead"); -} // onRead - - -/** - * @brief Callback function to support a write request. - * @param [in] pCharacteristic The characteristic that is the source of the event. - */ -void BLECharacteristicCallbacks::onWrite(BLECharacteristic *pCharacteristic) { - ESP_LOGD("BLECharacteristicCallbacks", ">> onWrite: default"); - ESP_LOGD("BLECharacteristicCallbacks", "<< onWrite"); -} // onWrite - -#endif /* CONFIG_BT_ENABLED */ diff --git a/lib/ESP32_BLE_Arduino/src/BLECharacteristic.h b/lib/ESP32_BLE_Arduino/src/BLECharacteristic.h deleted file mode 100644 index b3f8d2e9..00000000 --- a/lib/ESP32_BLE_Arduino/src/BLECharacteristic.h +++ /dev/null @@ -1,140 +0,0 @@ -/* - * BLECharacteristic.h - * - * Created on: Jun 22, 2017 - * Author: kolban - */ - -#ifndef COMPONENTS_CPP_UTILS_BLECHARACTERISTIC_H_ -#define COMPONENTS_CPP_UTILS_BLECHARACTERISTIC_H_ -#include "sdkconfig.h" -#if defined(CONFIG_BT_ENABLED) -#include -#include -#include "BLEUUID.h" -#include -#include -#include "BLEDescriptor.h" -#include "BLEValue.h" -#include "FreeRTOS.h" - -class BLEService; -class BLEDescriptor; -class BLECharacteristicCallbacks; - -/** - * @brief A management structure for %BLE descriptors. - */ -class BLEDescriptorMap { -public: - void setByUUID(const char* uuid, BLEDescriptor *pDescriptor); - void setByUUID(BLEUUID uuid, BLEDescriptor *pDescriptor); - void setByHandle(uint16_t handle, BLEDescriptor *pDescriptor); - BLEDescriptor* getByUUID(const char* uuid); - BLEDescriptor* getByUUID(BLEUUID uuid); - BLEDescriptor* getByHandle(uint16_t handle); - std::string toString(); - void handleGATTServerEvent( - esp_gatts_cb_event_t event, - esp_gatt_if_t gatts_if, - esp_ble_gatts_cb_param_t* param); - BLEDescriptor* getFirst(); - BLEDescriptor* getNext(); -private: - std::map m_uuidMap; - std::map m_handleMap; - std::map::iterator m_iterator; -}; - - -/** - * @brief The model of a %BLE Characteristic. - * - * A %BLE Characteristic is an identified value container that manages a value. It is exposed by a %BLE server and - * can be read and written to by a %BLE client. - */ -class BLECharacteristic { -public: - BLECharacteristic(const char* uuid, uint32_t properties = 0); - BLECharacteristic(BLEUUID uuid, uint32_t properties = 0); - virtual ~BLECharacteristic(); - - void addDescriptor(BLEDescriptor* pDescriptor); - BLEDescriptor* getDescriptorByUUID(const char* descriptorUUID); - BLEDescriptor* getDescriptorByUUID(BLEUUID descriptorUUID); - //size_t getLength(); - BLEUUID getUUID(); - std::string getValue(); - - void indicate(); - void notify(); - void setBroadcastProperty(bool value); - void setCallbacks(BLECharacteristicCallbacks* pCallbacks); - void setIndicateProperty(bool value); - void setNotifyProperty(bool value); - void setReadProperty(bool value); - void setValue(uint8_t* data, size_t size); - void setValue(std::string value); - void setValue(uint16_t& data16); - void setValue(uint32_t& data32); - void setValue(int& data32); - void setValue(float& data32); - void setValue(double& data64); - void setWriteProperty(bool value); - void setWriteNoResponseProperty(bool value); - std::string toString(); - uint16_t getHandle(); - void setAccessPermissions(esp_gatt_perm_t perm); - - static const uint32_t PROPERTY_READ = 1<<0; - static const uint32_t PROPERTY_WRITE = 1<<1; - static const uint32_t PROPERTY_NOTIFY = 1<<2; - static const uint32_t PROPERTY_BROADCAST = 1<<3; - static const uint32_t PROPERTY_INDICATE = 1<<4; - static const uint32_t PROPERTY_WRITE_NR = 1<<5; - -private: - - friend class BLEServer; - friend class BLEService; - friend class BLEDescriptor; - friend class BLECharacteristicMap; - - BLEUUID m_bleUUID; - BLEDescriptorMap m_descriptorMap; - uint16_t m_handle; - esp_gatt_char_prop_t m_properties; - BLECharacteristicCallbacks* m_pCallbacks; - BLEService* m_pService; - BLEValue m_value; - esp_gatt_perm_t m_permissions = ESP_GATT_PERM_READ | ESP_GATT_PERM_WRITE; - - void handleGATTServerEvent( - esp_gatts_cb_event_t event, - esp_gatt_if_t gatts_if, - esp_ble_gatts_cb_param_t* param); - - void executeCreate(BLEService* pService); - esp_gatt_char_prop_t getProperties(); - BLEService* getService(); - void setHandle(uint16_t handle); - FreeRTOS::Semaphore m_semaphoreCreateEvt = FreeRTOS::Semaphore("CreateEvt"); - FreeRTOS::Semaphore m_semaphoreConfEvt = FreeRTOS::Semaphore("ConfEvt"); -}; // BLECharacteristic - - -/** - * @brief Callbacks that can be associated with a %BLE characteristic to inform of events. - * - * When a server application creates a %BLE characteristic, we may wish to be informed when there is either - * a read or write request to the characteristic's value. An application can register a - * sub-classed instance of this class and will be notified when such an event happens. - */ -class BLECharacteristicCallbacks { -public: - virtual ~BLECharacteristicCallbacks(); - virtual void onRead(BLECharacteristic* pCharacteristic); - virtual void onWrite(BLECharacteristic* pCharacteristic); -}; -#endif /* CONFIG_BT_ENABLED */ -#endif /* COMPONENTS_CPP_UTILS_BLECHARACTERISTIC_H_ */ diff --git a/lib/ESP32_BLE_Arduino/src/BLECharacteristicMap.cpp b/lib/ESP32_BLE_Arduino/src/BLECharacteristicMap.cpp deleted file mode 100644 index 86a97441..00000000 --- a/lib/ESP32_BLE_Arduino/src/BLECharacteristicMap.cpp +++ /dev/null @@ -1,143 +0,0 @@ -/* - * BLECharacteristicMap.cpp - * - * Created on: Jun 22, 2017 - * Author: kolban - */ -#include "sdkconfig.h" -#if defined(CONFIG_BT_ENABLED) -#include -#include -#include "BLEService.h" -#ifdef ARDUINO_ARCH_ESP32 -#include "esp32-hal-log.h" -#endif - - -/** - * @brief Return the characteristic by handle. - * @param [in] handle The handle to look up the characteristic. - * @return The characteristic. - */ -BLECharacteristic* BLECharacteristicMap::getByHandle(uint16_t handle) { - return m_handleMap.at(handle); -} // getByHandle - - -/** - * @brief Return the characteristic by UUID. - * @param [in] UUID The UUID to look up the characteristic. - * @return The characteristic. - */ -BLECharacteristic* BLECharacteristicMap::getByUUID(const char* uuid) { - return getByUUID(BLEUUID(uuid)); -} - - -/** - * @brief Return the characteristic by UUID. - * @param [in] UUID The UUID to look up the characteristic. - * @return The characteristic. - */ -BLECharacteristic* BLECharacteristicMap::getByUUID(BLEUUID uuid) { - for (auto &myPair : m_uuidMap) { - if (myPair.first->getUUID().equals(uuid)) { - return myPair.first; - } - } - //return m_uuidMap.at(uuid.toString()); - return nullptr; -} // getByUUID - - -/** - * @brief Get the first characteristic in the map. - * @return The first characteristic in the map. - */ -BLECharacteristic* BLECharacteristicMap::getFirst() { - m_iterator = m_uuidMap.begin(); - if (m_iterator == m_uuidMap.end()) { - return nullptr; - } - BLECharacteristic* pRet = m_iterator->first; - m_iterator++; - return pRet; -} // getFirst - - -/** - * @brief Get the next characteristic in the map. - * @return The next characteristic in the map. - */ -BLECharacteristic* BLECharacteristicMap::getNext() { - if (m_iterator == m_uuidMap.end()) { - return nullptr; - } - BLECharacteristic* pRet = m_iterator->first; - m_iterator++; - return pRet; -} // getNext - - -/** - * @brief Pass the GATT server event onwards to each of the characteristics found in the mapping - * @param [in] event - * @param [in] gatts_if - * @param [in] param - */ -void BLECharacteristicMap::handleGATTServerEvent( - esp_gatts_cb_event_t event, - esp_gatt_if_t gatts_if, - esp_ble_gatts_cb_param_t* param) { - // Invoke the handler for every Service we have. - for (auto &myPair : m_uuidMap) { - myPair.first->handleGATTServerEvent(event, gatts_if, param); - } -} // handleGATTServerEvent - - -/** - * @brief Set the characteristic by handle. - * @param [in] handle The handle of the characteristic. - * @param [in] characteristic The characteristic to cache. - * @return N/A. - */ -void BLECharacteristicMap::setByHandle(uint16_t handle, - BLECharacteristic *characteristic) { - m_handleMap.insert(std::pair(handle, characteristic)); -} // setByHandle - - -/** - * @brief Set the characteristic by UUID. - * @param [in] uuid The uuid of the characteristic. - * @param [in] characteristic The characteristic to cache. - * @return N/A. - */ -void BLECharacteristicMap::setByUUID( - BLECharacteristic *pCharacteristic, - BLEUUID uuid) { - m_uuidMap.insert(std::pair(pCharacteristic, uuid.toString())); -} // setByUUID - - -/** - * @brief Return a string representation of the characteristic map. - * @return A string representation of the characteristic map. - */ -std::string BLECharacteristicMap::toString() { - std::stringstream stringStream; - stringStream << std::hex << std::setfill('0'); - int count=0; - for (auto &myPair: m_uuidMap) { - if (count > 0) { - stringStream << "\n"; - } - count++; - stringStream << "handle: 0x" << std::setw(2) << myPair.first->getHandle() << ", uuid: " + myPair.first->getUUID().toString(); - } - return stringStream.str(); -} // toString - - -#endif /* CONFIG_BT_ENABLED */ diff --git a/lib/ESP32_BLE_Arduino/src/BLEClient.cpp b/lib/ESP32_BLE_Arduino/src/BLEClient.cpp deleted file mode 100644 index 141cf0f5..00000000 --- a/lib/ESP32_BLE_Arduino/src/BLEClient.cpp +++ /dev/null @@ -1,471 +0,0 @@ -/* - * BLEDevice.cpp - * - * Created on: Mar 22, 2017 - * Author: kolban - */ -#include "sdkconfig.h" -#if defined(CONFIG_BT_ENABLED) -#include -#include -#include -#include -#include -#include "BLEClient.h" -#include "BLEUtils.h" -#include "BLEService.h" -#include "GeneralUtils.h" -#include -#include -#include -#ifdef ARDUINO_ARCH_ESP32 -#include "esp32-hal-log.h" -#endif - -/* - * Design - * ------ - * When we perform a searchService() requests, we are asking the BLE server to return each of the services - * that it exposes. For each service, we received an ESP_GATTC_SEARCH_RES_EVT event which contains details - * of the exposed service including its UUID. - * - * The objects we will invent for a BLEClient will be as follows: - * * BLERemoteService - A model of a remote service. - * * BLERemoteCharacteristic - A model of a remote characteristic - * * BLERemoteDescriptor - A model of a remote descriptor. - * - * Since there is a hierarchical relationship here, we will have the idea that from a BLERemoteService will own - * zero or more remote characteristics and a BLERemoteCharacteristic will own zero or more remote BLEDescriptors. - * - * We will assume that a BLERemoteService contains a map that maps BLEUUIDs to the set of owned characteristics - * and that a BLECharacteristic contains a map that maps BLEUUIDs to the set of owned descriptors. - * - * - */ -static const char* LOG_TAG = "BLEClient"; - -BLEClient::BLEClient() { - m_pClientCallbacks = nullptr; - m_conn_id = 0; - m_gattc_if = 0; - m_haveServices = false; - m_isConnected = false; // Initially, we are flagged as not connected. -} // BLEClient - - -/** - * @brief Destructor. - */ -BLEClient::~BLEClient() { - // We may have allocated service references associated with this client. Before we are finished - // with the client, we must release resources. - for (auto &myPair : m_servicesMap) { - delete myPair.second; - } - m_servicesMap.clear(); -} // ~BLEClient - - -/** - * @brief Clear any existing services. - * - */ -void BLEClient::clearServices() { - ESP_LOGD(LOG_TAG, ">> clearServices"); - // Delete all the services. - for (auto &myPair : m_servicesMap) { - delete myPair.second; - } - m_servicesMap.clear(); - m_haveServices = false; - ESP_LOGD(LOG_TAG, "<< clearServices"); -} // clearServices - - -/** - * @brief Connect to the partner (BLE Server). - * @param [in] address The address of the partner. - * @return True on success. - */ -bool BLEClient::connect(BLEAddress address) { - ESP_LOGD(LOG_TAG, ">> connect(%s)", address.toString().c_str()); - -// We need the connection handle that we get from registering the application. We register the app -// and then block on its completion. When the event has arrived, we will have the handle. - m_semaphoreRegEvt.take("connect"); - - clearServices(); // Delete any services that may exist. - - esp_err_t errRc = ::esp_ble_gattc_app_register(0); - if (errRc != ESP_OK) { - ESP_LOGE(LOG_TAG, "esp_ble_gattc_app_register: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return false; - } - - m_semaphoreRegEvt.wait("connect"); - - m_peerAddress = address; - - // Perform the open connection request against the target BLE Server. - m_semaphoreOpenEvt.take("connect"); - errRc = ::esp_ble_gattc_open( - getGattcIf(), - *getPeerAddress().getNative(), // address - BLE_ADDR_TYPE_PUBLIC, // Note: This was added on 2018-04-03 when the latest ESP-IDF was detected to have changed the signature. - 1 // direct connection - ); - if (errRc != ESP_OK) { - ESP_LOGE(LOG_TAG, "esp_ble_gattc_open: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return false; - } - - uint32_t rc = m_semaphoreOpenEvt.wait("connect"); // Wait for the connection to complete. - ESP_LOGD(LOG_TAG, "<< connect(), rc=%d", rc==ESP_GATT_OK); - return rc == ESP_GATT_OK; -} // connect - - -/** - * @brief Disconnect from the peer. - * @return N/A. - */ -void BLEClient::disconnect() { - ESP_LOGD(LOG_TAG, ">> disconnect()"); - esp_err_t errRc = ::esp_ble_gattc_close(getGattcIf(), getConnId()); - if (errRc != ESP_OK) { - ESP_LOGE(LOG_TAG, "esp_ble_gattc_close: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return; - } - esp_ble_gattc_app_unregister(getGattcIf()); - m_peerAddress = BLEAddress("00:00:00:00:00:00"); - ESP_LOGD(LOG_TAG, "<< disconnect()"); -} // disconnect - - -/** - * @brief Handle GATT Client events - */ -void BLEClient::gattClientEventHandler( - esp_gattc_cb_event_t event, - esp_gatt_if_t gattc_if, - esp_ble_gattc_cb_param_t* evtParam) { - - // Execute handler code based on the type of event received. - switch(event) { - - // - // ESP_GATTC_DISCONNECT_EVT - // - // disconnect: - // - esp_gatt_status_t status - // - uint16_t conn_id - // - esp_bd_addr_t remote_bda - case ESP_GATTC_DISCONNECT_EVT: { - // If we receive a disconnect event, set the class flag that indicates that we are - // no longer connected. - if (m_pClientCallbacks != nullptr) { - m_pClientCallbacks->onDisconnect(this); - } - m_isConnected = false; - m_semaphoreRssiCmplEvt.give(); - m_semaphoreSearchCmplEvt.give(1); - break; - } // ESP_GATTC_DISCONNECT_EVT - - // - // ESP_GATTC_OPEN_EVT - // - // open: - // - esp_gatt_status_t status - // - uint16_t conn_id - // - esp_bd_addr_t remote_bda - // - uint16_t mtu - // - case ESP_GATTC_OPEN_EVT: { - m_conn_id = evtParam->open.conn_id; - if (m_pClientCallbacks != nullptr) { - m_pClientCallbacks->onConnect(this); - } - if (evtParam->open.status == ESP_GATT_OK) { - m_isConnected = true; // Flag us as connected. - } - m_semaphoreOpenEvt.give(evtParam->open.status); - break; - } // ESP_GATTC_OPEN_EVT - - - // - // ESP_GATTC_REG_EVT - // - // reg: - // esp_gatt_status_t status - // uint16_t app_id - // - case ESP_GATTC_REG_EVT: { - m_gattc_if = gattc_if; - m_semaphoreRegEvt.give(); - break; - } // ESP_GATTC_REG_EVT - - - // - // ESP_GATTC_SEARCH_CMPL_EVT - // - // search_cmpl: - // - esp_gatt_status_t status - // - uint16_t conn_id - // - case ESP_GATTC_SEARCH_CMPL_EVT: { - m_semaphoreSearchCmplEvt.give(0); - break; - } // ESP_GATTC_SEARCH_CMPL_EVT - - - // - // ESP_GATTC_SEARCH_RES_EVT - // - // search_res: - // - uint16_t conn_id - // - uint16_t start_handle - // - uint16_t end_handle - // - esp_gatt_id_t srvc_id - // - case ESP_GATTC_SEARCH_RES_EVT: { - BLEUUID uuid = BLEUUID(evtParam->search_res.srvc_id); - BLERemoteService* pRemoteService = new BLERemoteService( - evtParam->search_res.srvc_id, - this, - evtParam->search_res.start_handle, - evtParam->search_res.end_handle - ); - m_servicesMap.insert(std::pair(uuid.toString(), pRemoteService)); - break; - } // ESP_GATTC_SEARCH_RES_EVT - - - default: { - break; - } - } // Switch - - // Pass the request on to all services. - for (auto &myPair : m_servicesMap) { - myPair.second->gattClientEventHandler(event, gattc_if, evtParam); - } - -} // gattClientEventHandler - - -uint16_t BLEClient::getConnId() { - return m_conn_id; -} // getConnId - - - -esp_gatt_if_t BLEClient::getGattcIf() { - return m_gattc_if; -} // getGattcIf - - -/** - * @brief Retrieve the address of the peer. - * - * Returns the Bluetooth device address of the %BLE peer to which this client is connected. - */ -BLEAddress BLEClient::getPeerAddress() { - return m_peerAddress; -} // getAddress - - -/** - * @brief Ask the BLE server for the RSSI value. - * @return The RSSI value. - */ -int BLEClient::getRssi() { - ESP_LOGD(LOG_TAG, ">> getRssi()"); - if (!isConnected()) { - ESP_LOGD(LOG_TAG, "<< getRssi(): Not connected"); - return 0; - } - // We make the API call to read the RSSI value which is an asynchronous operation. We expect to receive - // an ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT to indicate completion. - // - m_semaphoreRssiCmplEvt.take("getRssi"); - esp_err_t rc = ::esp_ble_gap_read_rssi(*getPeerAddress().getNative()); - if (rc != ESP_OK) { - ESP_LOGE(LOG_TAG, "<< getRssi: esp_ble_gap_read_rssi: rc=%d %s", rc, GeneralUtils::errorToString(rc)); - return 0; - } - int rssiValue = m_semaphoreRssiCmplEvt.wait("getRssi"); - ESP_LOGD(LOG_TAG, "<< getRssi(): %d", rssiValue); - return rssiValue; -} // getRssi - - -/** - * @brief Get the service BLE Remote Service instance corresponding to the uuid. - * @param [in] uuid The UUID of the service being sought. - * @return A reference to the Service or nullptr if don't know about it. - */ -BLERemoteService* BLEClient::getService(const char* uuid) { - return getService(BLEUUID(uuid)); -} // getService - - -/** - * @brief Get the service object corresponding to the uuid. - * @param [in] uuid The UUID of the service being sought. - * @return A reference to the Service or nullptr if don't know about it. - * @throws BLEUuidNotFound - */ -BLERemoteService* BLEClient::getService(BLEUUID uuid) { - ESP_LOGD(LOG_TAG, ">> getService: uuid: %s", uuid.toString().c_str()); -// Design -// ------ -// We wish to retrieve the service given its UUID. It is possible that we have not yet asked the -// device what services it has in which case we have nothing to match against. If we have not -// asked the device about its services, then we do that now. Once we get the results we can then -// examine the services map to see if it has the service we are looking for. - if (!m_haveServices) { - getServices(); - } - std::string uuidStr = uuid.toString(); - for (auto &myPair : m_servicesMap) { - if (myPair.first == uuidStr) { - ESP_LOGD(LOG_TAG, "<< getService: found the service with uuid: %s", uuid.toString().c_str()); - return myPair.second; - } - } // End of each of the services. - ESP_LOGD(LOG_TAG, "<< getService: not found"); - throw new BLEUuidNotFoundException; -} // getService - - -/** - * @brief Ask the remote %BLE server for its services. - * A %BLE Server exposes a set of services for its partners. Here we ask the server for its set of - * services and wait until we have received them all. - * @return N/A - */ -std::map* BLEClient::getServices() { -/* - * Design - * ------ - * We invoke esp_ble_gattc_search_service. This will request a list of the service exposed by the - * peer BLE partner to be returned as events. Each event will be an an instance of ESP_GATTC_SEARCH_RES_EVT - * and will culminate with an ESP_GATTC_SEARCH_CMPL_EVT when all have been received. - */ - ESP_LOGD(LOG_TAG, ">> getServices"); - - clearServices(); // Clear any services that may exist. - - esp_err_t errRc = esp_ble_gattc_search_service( - getGattcIf(), - getConnId(), - nullptr // Filter UUID - ); - m_semaphoreSearchCmplEvt.take("getServices"); - if (errRc != ESP_OK) { - ESP_LOGE(LOG_TAG, "esp_ble_gattc_search_service: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return &m_servicesMap; - } - // If sucessfull, remember that we now have services. - m_haveServices = (m_semaphoreSearchCmplEvt.wait("getServices") == 0); - ESP_LOGD(LOG_TAG, "<< getServices"); - return &m_servicesMap; -} // getServices - - -/** - * @brief Get the value of a specific characteristic associated with a specific service. - * @param [in] serviceUUID The service that owns the characteristic. - * @param [in] characteristicUUID The characteristic whose value we wish to read. - * @throws BLEUuidNotFound - */ -std::string BLEClient::getValue(BLEUUID serviceUUID, BLEUUID characteristicUUID) { - ESP_LOGD(LOG_TAG, ">> getValue: serviceUUID: %s, characteristicUUID: %s", serviceUUID.toString().c_str(), characteristicUUID.toString().c_str()); - std::string ret = getService(serviceUUID)->getCharacteristic(characteristicUUID)->readValue(); - ESP_LOGD(LOG_TAG, "<read_rssi_cmpl.rssi); - break; - } // ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT - - default: - break; - } -} // handleGAPEvent - - -/** - * @brief Are we connected to a partner? - * @return True if we are connected and false if we are not connected. - */ -bool BLEClient::isConnected() { - return m_isConnected; -} // isConnected - - - - -/** - * @brief Set the callbacks that will be invoked. - */ -void BLEClient::setClientCallbacks(BLEClientCallbacks* pClientCallbacks) { - m_pClientCallbacks = pClientCallbacks; -} // setClientCallbacks - - -/** - * @brief Set the value of a specific characteristic associated with a specific service. - * @param [in] serviceUUID The service that owns the characteristic. - * @param [in] characteristicUUID The characteristic whose value we wish to write. - * @throws BLEUuidNotFound - */ -void BLEClient::setValue(BLEUUID serviceUUID, BLEUUID characteristicUUID, std::string value) { - ESP_LOGD(LOG_TAG, ">> setValue: serviceUUID: %s, characteristicUUID: %s", serviceUUID.toString().c_str(), characteristicUUID.toString().c_str()); - getService(serviceUUID)->getCharacteristic(characteristicUUID)->writeValue(value); - ESP_LOGD(LOG_TAG, "<< setValue"); -} // setValue - - -/** - * @brief Return a string representation of this client. - * @return A string representation of this client. - */ -std::string BLEClient::toString() { - std::ostringstream ss; - ss << "peer address: " << m_peerAddress.toString(); - ss << "\nServices:\n"; - for (auto &myPair : m_servicesMap) { - ss << myPair.second->toString() << "\n"; - // myPair.second is the value - } - return ss.str(); -} // toString - - -#endif // CONFIG_BT_ENABLED diff --git a/lib/ESP32_BLE_Arduino/src/BLEClient.h b/lib/ESP32_BLE_Arduino/src/BLEClient.h deleted file mode 100644 index a60ed102..00000000 --- a/lib/ESP32_BLE_Arduino/src/BLEClient.h +++ /dev/null @@ -1,98 +0,0 @@ -/* - * BLEDevice.h - * - * Created on: Mar 22, 2017 - * Author: kolban - */ - -#ifndef MAIN_BLEDEVICE_H_ -#define MAIN_BLEDEVICE_H_ - -#include "sdkconfig.h" -#if defined(CONFIG_BT_ENABLED) - -#include -#include -#include -#include -#include "BLEExceptions.h" -#include "BLERemoteService.h" -#include "BLEService.h" -#include "BLEAddress.h" - -class BLERemoteService; -class BLEClientCallbacks; - -/** - * @brief A model of a %BLE client. - */ -class BLEClient { -public: - BLEClient(); - ~BLEClient(); - - bool connect(BLEAddress address); // Connect to the remote BLE Server - void disconnect(); // Disconnect from the remote BLE Server - BLEAddress getPeerAddress(); // Get the address of the remote BLE Server - int getRssi(); // Get the RSSI of the remote BLE Server - std::map* getServices(); // Get a map of the services offered by the remote BLE Server - BLERemoteService* getService(const char* uuid); // Get a reference to a specified service offered by the remote BLE server. - BLERemoteService* getService(BLEUUID uuid); // Get a reference to a specified service offered by the remote BLE server. - std::string getValue(BLEUUID serviceUUID, BLEUUID characteristicUUID); // Get the value of a given characteristic at a given service. - - - void handleGAPEvent( - esp_gap_ble_cb_event_t event, - esp_ble_gap_cb_param_t* param); - - bool isConnected(); // Return true if we are connected. - - void setClientCallbacks(BLEClientCallbacks *pClientCallbacks); - void setValue(BLEUUID serviceUUID, BLEUUID characteristicUUID, std::string value); // Set the value of a given characteristic at a given service. - - std::string toString(); // Return a string representation of this client. - - -private: - friend class BLEDevice; - friend class BLERemoteService; - friend class BLERemoteCharacteristic; - friend class BLERemoteDescriptor; - - void gattClientEventHandler( - esp_gattc_cb_event_t event, - esp_gatt_if_t gattc_if, - esp_ble_gattc_cb_param_t* param); - - uint16_t getConnId(); - esp_gatt_if_t getGattcIf(); - BLEAddress m_peerAddress = BLEAddress((uint8_t*)"\0\0\0\0\0\0"); // The BD address of the remote server. - uint16_t m_conn_id; -// int m_deviceType; - esp_gatt_if_t m_gattc_if; - bool m_haveServices; // Have we previously obtain the set of services from the remote server. - bool m_isConnected; // Are we currently connected. - - BLEClientCallbacks* m_pClientCallbacks; - FreeRTOS::Semaphore m_semaphoreRegEvt = FreeRTOS::Semaphore("RegEvt"); - FreeRTOS::Semaphore m_semaphoreOpenEvt = FreeRTOS::Semaphore("OpenEvt"); - FreeRTOS::Semaphore m_semaphoreSearchCmplEvt = FreeRTOS::Semaphore("SearchCmplEvt"); - FreeRTOS::Semaphore m_semaphoreRssiCmplEvt = FreeRTOS::Semaphore("RssiCmplEvt"); - std::map m_servicesMap; - void clearServices(); // Clear any existing services. - -}; // class BLEDevice - - -/** - * @brief Callbacks associated with a %BLE client. - */ -class BLEClientCallbacks { -public: - virtual ~BLEClientCallbacks() {}; - virtual void onConnect(BLEClient *pClient) = 0; - virtual void onDisconnect(BLEClient *pClient) = 0; -}; - -#endif // CONFIG_BT_ENABLED -#endif /* MAIN_BLEDEVICE_H_ */ diff --git a/lib/ESP32_BLE_Arduino/src/BLEDescriptor.cpp b/lib/ESP32_BLE_Arduino/src/BLEDescriptor.cpp deleted file mode 100644 index 58ff78b4..00000000 --- a/lib/ESP32_BLE_Arduino/src/BLEDescriptor.cpp +++ /dev/null @@ -1,342 +0,0 @@ -/* - * BLEDescriptor.cpp - * - * Created on: Jun 22, 2017 - * Author: kolban - */ -#include "sdkconfig.h" -#if defined(CONFIG_BT_ENABLED) -#include -#include -#include -#include -#include "sdkconfig.h" -#include -#include -#include "BLEService.h" -#include "BLEDescriptor.h" -#include "GeneralUtils.h" -#ifdef ARDUINO_ARCH_ESP32 -#include "esp32-hal-log.h" -#endif - -static const char* LOG_TAG = "BLEDescriptor"; - - -#define NULL_HANDLE (0xffff) - - -/** - * @brief BLEDescriptor constructor. - */ -BLEDescriptor::BLEDescriptor(const char* uuid) : BLEDescriptor(BLEUUID(uuid)) { -} - -/** - * @brief BLEDescriptor constructor. - */ -BLEDescriptor::BLEDescriptor(BLEUUID uuid) { - m_bleUUID = uuid; - m_value.attr_value = (uint8_t *)malloc(ESP_GATT_MAX_ATTR_LEN); // Allocate storage for the value. - m_value.attr_len = 0; // Initial length is 0. - m_value.attr_max_len = ESP_GATT_MAX_ATTR_LEN; // Maximum length of the data. - m_handle = NULL_HANDLE; // Handle is initially unknown. - m_pCharacteristic = nullptr; // No initial characteristic. - m_pCallback = nullptr; // No initial callback. - -} // BLEDescriptor - - -/** - * @brief BLEDescriptor destructor. - */ -BLEDescriptor::~BLEDescriptor() { - free(m_value.attr_value); // Release the storage we created in the constructor. -} // ~BLEDescriptor - - -/** - * @brief Execute the creation of the descriptor with the BLE runtime in ESP. - * @param [in] pCharacteristic The characteristic to which to register this descriptor. - */ -void BLEDescriptor::executeCreate(BLECharacteristic* pCharacteristic) { - ESP_LOGD(LOG_TAG, ">> executeCreate(): %s", toString().c_str()); - - if (m_handle != NULL_HANDLE) { - ESP_LOGE(LOG_TAG, "Descriptor already has a handle."); - return; - } - - m_pCharacteristic = pCharacteristic; // Save the characteristic associated with this service. - - esp_attr_control_t control; - control.auto_rsp = ESP_GATT_RSP_BY_APP; - m_semaphoreCreateEvt.take("executeCreate"); - esp_err_t errRc = ::esp_ble_gatts_add_char_descr( - pCharacteristic->getService()->getHandle(), - getUUID().getNative(), - (esp_gatt_perm_t)(ESP_GATT_PERM_READ | ESP_GATT_PERM_WRITE), - &m_value, - &control); - if (errRc != ESP_OK) { - ESP_LOGE(LOG_TAG, "<< esp_ble_gatts_add_char_descr: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return; - } - - m_semaphoreCreateEvt.wait("executeCreate"); - ESP_LOGD(LOG_TAG, "<< executeCreate"); -} // executeCreate - - -/** - * @brief Get the BLE handle for this descriptor. - * @return The handle for this descriptor. - */ -uint16_t BLEDescriptor::getHandle() { - return m_handle; -} // getHandle - - -/** - * @brief Get the length of the value of this descriptor. - * @return The length (in bytes) of the value of this descriptor. - */ -size_t BLEDescriptor::getLength() { - return m_value.attr_len; -} // getLength - - -/** - * @brief Get the UUID of the descriptor. - */ -BLEUUID BLEDescriptor::getUUID() { - return m_bleUUID; -} // getUUID - - - -/** - * @brief Get the value of this descriptor. - * @return A pointer to the value of this descriptor. - */ -uint8_t* BLEDescriptor::getValue() { - return m_value.attr_value; -} // getValue - - -/** - * @brief Handle GATT server events for the descripttor. - * @param [in] event - * @param [in] gatts_if - * @param [in] param - */ -void BLEDescriptor::handleGATTServerEvent( - esp_gatts_cb_event_t event, - esp_gatt_if_t gatts_if, - esp_ble_gatts_cb_param_t *param) { - switch(event) { - // ESP_GATTS_ADD_CHAR_DESCR_EVT - // - // add_char_descr: - // - esp_gatt_status_t status - // - uint16_t attr_handle - // - uint16_t service_handle - // - esp_bt_uuid_t char_uuid - case ESP_GATTS_ADD_CHAR_DESCR_EVT: { - /* - ESP_LOGD(LOG_TAG, "DEBUG: m_pCharacteristic: %x", (uint32_t)m_pCharacteristic); - ESP_LOGD(LOG_TAG, "DEBUG: m_bleUUID: %s, add_char_descr.char_uuid: %s, equals: %d", - m_bleUUID.toString().c_str(), - BLEUUID(param->add_char_descr.char_uuid).toString().c_str(), - m_bleUUID.equals(BLEUUID(param->add_char_descr.char_uuid))); - ESP_LOGD(LOG_TAG, "DEBUG: service->getHandle: %x, add_char_descr.service_handle: %x", - m_pCharacteristic->getService()->getHandle(), param->add_char_descr.service_handle); - ESP_LOGD(LOG_TAG, "DEBUG: service->lastCharacteristic: %x", - (uint32_t)m_pCharacteristic->getService()->getLastCreatedCharacteristic()); - */ - if (m_pCharacteristic != nullptr && - m_bleUUID.equals(BLEUUID(param->add_char_descr.descr_uuid)) && - m_pCharacteristic->getService()->getHandle() == param->add_char_descr.service_handle && - m_pCharacteristic == m_pCharacteristic->getService()->getLastCreatedCharacteristic()) { - setHandle(param->add_char_descr.attr_handle); - m_semaphoreCreateEvt.give(); - } - break; - } // ESP_GATTS_ADD_CHAR_DESCR_EVT - - // ESP_GATTS_WRITE_EVT - A request to write the value of a descriptor has arrived. - // - // write: - // - uint16_t conn_id - // - uint16_t trans_id - // - esp_bd_addr_t bda - // - uint16_t handle - // - uint16_t offset - // - bool need_rsp - // - bool is_prep - // - uint16_t len - // - uint8_t *value - case ESP_GATTS_WRITE_EVT: { - if (param->write.handle == m_handle) { - setValue(param->write.value, param->write.len); // Set the value of the descriptor. - - esp_gatt_rsp_t rsp; // Build a response. - rsp.attr_value.len = getLength(); - rsp.attr_value.handle = m_handle; - rsp.attr_value.offset = 0; - rsp.attr_value.auth_req = ESP_GATT_AUTH_REQ_NONE; - memcpy(rsp.attr_value.value, getValue(), rsp.attr_value.len); - esp_err_t errRc = ::esp_ble_gatts_send_response( - gatts_if, - param->write.conn_id, - param->write.trans_id, - ESP_GATT_OK, - &rsp); - - if (errRc != ESP_OK) { // Check the return code from the send of the response. - ESP_LOGE(LOG_TAG, "esp_ble_gatts_send_response: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - } - - if (m_pCallback != nullptr) { // We have completed the write, if there is a user supplied callback handler, invoke it now. - m_pCallback->onWrite(this); // Invoke the onWrite callback handler. - } - } // End of ... this is our handle. - - break; - } // ESP_GATTS_WRITE_EVT - - // ESP_GATTS_READ_EVT - A request to read the value of a descriptor has arrived. - // - // read: - // - uint16_t conn_id - // - uint32_t trans_id - // - esp_bd_addr_t bda - // - uint16_t handle - // - uint16_t offset - // - bool is_long - // - bool need_rsp - // - case ESP_GATTS_READ_EVT: { - if (param->read.handle == m_handle) { // If this event is for this descriptor ... process it - - if (m_pCallback != nullptr) { // If we have a user supplied callback, invoke it now. - m_pCallback->onRead(this); // Invoke the onRead callback method in the callback handler. - } - - if (param->read.need_rsp) { // Do we need a response - ESP_LOGD(LOG_TAG, "Sending a response (esp_ble_gatts_send_response)"); - esp_gatt_rsp_t rsp; - rsp.attr_value.len = getLength(); - rsp.attr_value.handle = param->read.handle; - rsp.attr_value.offset = 0; - rsp.attr_value.auth_req = ESP_GATT_AUTH_REQ_NONE; - memcpy(rsp.attr_value.value, getValue(), rsp.attr_value.len); - - esp_err_t errRc = ::esp_ble_gatts_send_response( - gatts_if, - param->read.conn_id, - param->read.trans_id, - ESP_GATT_OK, - &rsp); - - if (errRc != ESP_OK) { // Check the return code from the send of the response. - ESP_LOGE(LOG_TAG, "esp_ble_gatts_send_response: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - } - } // End of need a response. - } // End of this is our handle - break; - } // ESP_GATTS_READ_EVT - - default: { - break; - } - }// switch event -} // handleGATTServerEvent - - -/** - * @brief Set the callback handlers for this descriptor. - * @param [in] pCallbacks An instance of a callback structure used to define any callbacks for the descriptor. - */ -void BLEDescriptor::setCallbacks(BLEDescriptorCallbacks* pCallback) { - ESP_LOGD(LOG_TAG, ">> setCallbacks: 0x%x", (uint32_t)pCallback); - m_pCallback = pCallback; - ESP_LOGD(LOG_TAG, "<< setCallbacks"); -} // setCallbacks - - -/** - * @brief Set the handle of this descriptor. - * Set the handle of this descriptor to be the supplied value. - * @param [in] handle The handle to be associated with this descriptor. - * @return N/A. - */ -void BLEDescriptor::setHandle(uint16_t handle) { - ESP_LOGD(LOG_TAG, ">> setHandle(0x%.2x): Setting descriptor handle to be 0x%.2x", handle, handle); - m_handle = handle; - ESP_LOGD(LOG_TAG, "<< setHandle()"); -} // setHandle - - -/** - * @brief Set the value of the descriptor. - * @param [in] data The data to set for the descriptor. - * @param [in] length The length of the data in bytes. - */ -void BLEDescriptor::setValue(uint8_t* data, size_t length) { - if (length > ESP_GATT_MAX_ATTR_LEN) { - ESP_LOGE(LOG_TAG, "Size %d too large, must be no bigger than %d", length, ESP_GATT_MAX_ATTR_LEN); - return; - } - m_value.attr_len = length; - memcpy(m_value.attr_value, data, length); -} // setValue - - -/** - * @brief Set the value of the descriptor. - * @param [in] value The value of the descriptor in string form. - */ -void BLEDescriptor::setValue(std::string value) { - setValue((uint8_t *)value.data(), value.length()); -} // setValue - -void BLEDescriptor::setAccessPermissions(esp_gatt_perm_t perm) { - m_permissions = perm; -} - -/** - * @brief Return a string representation of the descriptor. - * @return A string representation of the descriptor. - */ -std::string BLEDescriptor::toString() { - std::stringstream stringstream; - stringstream << std::hex << std::setfill('0'); - stringstream << "UUID: " << m_bleUUID.toString() + ", handle: 0x" << std::setw(2) << m_handle; - return stringstream.str(); -} // toString - - -BLEDescriptorCallbacks::~BLEDescriptorCallbacks() {} - -/** - * @brief Callback function to support a read request. - * @param [in] pDescriptor The descriptor that is the source of the event. - */ -void BLEDescriptorCallbacks::onRead(BLEDescriptor* pDescriptor) { - ESP_LOGD("BLEDescriptorCallbacks", ">> onRead: default"); - ESP_LOGD("BLEDescriptorCallbacks", "<< onRead"); -} // onRead - - -/** - * @brief Callback function to support a write request. - * @param [in] pDescriptor The descriptor that is the source of the event. - */ -void BLEDescriptorCallbacks::onWrite(BLEDescriptor* pDescriptor) { - ESP_LOGD("BLEDescriptorCallbacks", ">> onWrite: default"); - ESP_LOGD("BLEDescriptorCallbacks", "<< onWrite"); -} // onWrite - - -#endif /* CONFIG_BT_ENABLED */ diff --git a/lib/ESP32_BLE_Arduino/src/BLEDescriptor.h b/lib/ESP32_BLE_Arduino/src/BLEDescriptor.h deleted file mode 100644 index d9e0aefb..00000000 --- a/lib/ESP32_BLE_Arduino/src/BLEDescriptor.h +++ /dev/null @@ -1,77 +0,0 @@ -/* - * BLEDescriptor.h - * - * Created on: Jun 22, 2017 - * Author: kolban - */ - -#ifndef COMPONENTS_CPP_UTILS_BLEDESCRIPTOR_H_ -#define COMPONENTS_CPP_UTILS_BLEDESCRIPTOR_H_ -#include "sdkconfig.h" -#if defined(CONFIG_BT_ENABLED) -#include -#include "BLEUUID.h" -#include "BLECharacteristic.h" -#include -#include "FreeRTOS.h" - -class BLEService; -class BLECharacteristic; -class BLEDescriptorCallbacks; - -/** - * @brief A model of a %BLE descriptor. - */ -class BLEDescriptor { -public: - BLEDescriptor(const char* uuid); - BLEDescriptor(BLEUUID uuid); - virtual ~BLEDescriptor(); - - uint16_t getHandle(); // Get the handle of the descriptor. - size_t getLength(); // Get the length of the value of the descriptor. - BLEUUID getUUID(); // Get the UUID of the descriptor. - uint8_t* getValue(); // Get a pointer to the value of the descriptor. - void handleGATTServerEvent( - esp_gatts_cb_event_t event, - esp_gatt_if_t gatts_if, - esp_ble_gatts_cb_param_t* param); - - void setAccessPermissions(esp_gatt_perm_t perm); // Set the permissions of the descriptor. - void setCallbacks(BLEDescriptorCallbacks* pCallbacks); // Set callbacks to be invoked for the descriptor. - void setValue(uint8_t* data, size_t size); // Set the value of the descriptor as a pointer to data. - void setValue(std::string value); // Set the value of the descriptor as a data buffer. - - std::string toString(); // Convert the descriptor to a string representation. - -private: - friend class BLEDescriptorMap; - friend class BLECharacteristic; - BLEUUID m_bleUUID; - uint16_t m_handle; - BLEDescriptorCallbacks* m_pCallback; - BLECharacteristic* m_pCharacteristic; - esp_gatt_perm_t m_permissions = ESP_GATT_PERM_READ | ESP_GATT_PERM_WRITE; - FreeRTOS::Semaphore m_semaphoreCreateEvt = FreeRTOS::Semaphore("CreateEvt"); - esp_attr_value_t m_value; - - void executeCreate(BLECharacteristic* pCharacteristic); - void setHandle(uint16_t handle); -}; // BLEDescriptor - - -/** - * @brief Callbacks that can be associated with a %BLE descriptors to inform of events. - * - * When a server application creates a %BLE descriptor, we may wish to be informed when there is either - * a read or write request to the descriptors value. An application can register a - * sub-classed instance of this class and will be notified when such an event happens. - */ -class BLEDescriptorCallbacks { -public: - virtual ~BLEDescriptorCallbacks(); - virtual void onRead(BLEDescriptor* pDescriptor); - virtual void onWrite(BLEDescriptor* pDescriptor); -}; -#endif /* CONFIG_BT_ENABLED */ -#endif /* COMPONENTS_CPP_UTILS_BLEDESCRIPTOR_H_ */ diff --git a/lib/ESP32_BLE_Arduino/src/BLEDescriptorMap.cpp b/lib/ESP32_BLE_Arduino/src/BLEDescriptorMap.cpp deleted file mode 100644 index 4e372e1d..00000000 --- a/lib/ESP32_BLE_Arduino/src/BLEDescriptorMap.cpp +++ /dev/null @@ -1,152 +0,0 @@ -/* - * BLEDescriptorMap.cpp - * - * Created on: Jun 22, 2017 - * Author: kolban - */ -#include "sdkconfig.h" -#if defined(CONFIG_BT_ENABLED) -#include -#include -#include "BLECharacteristic.h" -#include "BLEDescriptor.h" -#include // ESP32 BLE -#ifdef ARDUINO_ARCH_ESP32 -#include "esp32-hal-log.h" -#endif - -/** - * @brief Return the descriptor by UUID. - * @param [in] UUID The UUID to look up the descriptor. - * @return The descriptor. If not present, then nullptr is returned. - */ -BLEDescriptor* BLEDescriptorMap::getByUUID(const char* uuid) { - return getByUUID(BLEUUID(uuid)); -} - - -/** - * @brief Return the descriptor by UUID. - * @param [in] UUID The UUID to look up the descriptor. - * @return The descriptor. If not present, then nullptr is returned. - */ -BLEDescriptor* BLEDescriptorMap::getByUUID(BLEUUID uuid) { - for (auto &myPair : m_uuidMap) { - if (myPair.second->getUUID().equals(uuid)) { - return myPair.second; - } - } - //return m_uuidMap.at(uuid.toString()); - return nullptr; -} // getByUUID - - -/** - * @brief Return the descriptor by handle. - * @param [in] handle The handle to look up the descriptor. - * @return The descriptor. - */ -BLEDescriptor* BLEDescriptorMap::getByHandle(uint16_t handle) { - return m_handleMap.at(handle); -} // getByHandle - - -/** - * @brief Set the descriptor by UUID. - * @param [in] uuid The uuid of the descriptor. - * @param [in] characteristic The descriptor to cache. - * @return N/A. - */ -void BLEDescriptorMap::setByUUID(const char* uuid, BLEDescriptor *pDescriptor){ - m_uuidMap.insert(std::pair(uuid, pDescriptor)); -} // setByUUID - - - -/** - * @brief Set the descriptor by UUID. - * @param [in] uuid The uuid of the descriptor. - * @param [in] characteristic The descriptor to cache. - * @return N/A. - */ -void BLEDescriptorMap::setByUUID(BLEUUID uuid, BLEDescriptor *pDescriptor) { - m_uuidMap.insert(std::pair(uuid.toString(), pDescriptor)); -} // setByUUID - - -/** - * @brief Set the descriptor by handle. - * @param [in] handle The handle of the descriptor. - * @param [in] descriptor The descriptor to cache. - * @return N/A. - */ -void BLEDescriptorMap::setByHandle(uint16_t handle, - BLEDescriptor *pDescriptor) { - m_handleMap.insert(std::pair(handle, pDescriptor)); -} // setByHandle - - -/** - * @brief Return a string representation of the descriptor map. - * @return A string representation of the descriptor map. - */ -std::string BLEDescriptorMap::toString() { - std::stringstream stringStream; - stringStream << std::hex << std::setfill('0'); - int count=0; - for (auto &myPair: m_uuidMap) { - if (count > 0) { - stringStream << "\n"; - } - count++; - stringStream << "handle: 0x" << std::setw(2) << myPair.second->getHandle() << ", uuid: " + myPair.second->getUUID().toString(); - } - return stringStream.str(); -} // toString - - -/** - * @breif Pass the GATT server event onwards to each of the descriptors found in the mapping - * @param [in] event - * @param [in] gatts_if - * @param [in] param - */ -void BLEDescriptorMap::handleGATTServerEvent( - esp_gatts_cb_event_t event, - esp_gatt_if_t gatts_if, - esp_ble_gatts_cb_param_t *param) { - // Invoke the handler for every descriptor we have. - for (auto &myPair : m_uuidMap) { - myPair.second->handleGATTServerEvent(event, gatts_if, param); - } -} // handleGATTServerEvent - - -/** - * @brief Get the first descriptor in the map. - * @return The first descriptor in the map. - */ -BLEDescriptor* BLEDescriptorMap::getFirst() { - m_iterator = m_uuidMap.begin(); - if (m_iterator == m_uuidMap.end()) { - return nullptr; - } - BLEDescriptor *pRet = m_iterator->second; - m_iterator++; - return pRet; -} // getFirst - - -/** - * @brief Get the next descriptor in the map. - * @return The next descriptor in the map. - */ -BLEDescriptor* BLEDescriptorMap::getNext() { - if (m_iterator == m_uuidMap.end()) { - return nullptr; - } - BLEDescriptor *pRet = m_iterator->second; - m_iterator++; - return pRet; -} // getNext -#endif /* CONFIG_BT_ENABLED */ diff --git a/lib/ESP32_BLE_Arduino/src/BLEDevice.cpp b/lib/ESP32_BLE_Arduino/src/BLEDevice.cpp deleted file mode 100644 index a7db454b..00000000 --- a/lib/ESP32_BLE_Arduino/src/BLEDevice.cpp +++ /dev/null @@ -1,548 +0,0 @@ -/* - * BLE.cpp - * - * Created on: Mar 16, 2017 - * Author: kolban - */ -#include "sdkconfig.h" -#if defined(CONFIG_BT_ENABLED) -#include -#include -#include -#include -#include -#include // ESP32 BLE -#include // ESP32 BLE -#include // ESP32 BLE -#include // ESP32 BLE -#include // ESP32 BLE -#include // ESP32 BLE -#include // ESP32 BLE -#include // ESP32 ESP-IDF -#include // ESP32 ESP-IDF -#include // Part of C++ Standard library -#include // Part of C++ Standard library -#include // Part of C++ Standard library - -#include "BLEDevice.h" -#include "BLEClient.h" -#include "BLEUtils.h" -#include "GeneralUtils.h" -#ifdef ARDUINO_ARCH_ESP32 -#include "esp32-hal-log.h" -#include "esp32-hal-bt.h" -#endif - -static const char* LOG_TAG = "BLEDevice"; - -/** - * Singletons for the BLEDevice. - */ -BLEServer* BLEDevice::m_pServer = nullptr; -BLEScan* BLEDevice::m_pScan = nullptr; -BLEClient* BLEDevice::m_pClient = nullptr; -bool initialized = false; // Have we been initialized? -esp_ble_sec_act_t BLEDevice::m_securityLevel = (esp_ble_sec_act_t)0; -BLESecurityCallbacks* BLEDevice::m_securityCallbacks = nullptr; -uint16_t BLEDevice::m_localMTU = 23; - -/** - * @brief Create a new instance of a client. - * @return A new instance of the client. - */ -/* STATIC */ BLEClient* BLEDevice::createClient() { - ESP_LOGD(LOG_TAG, ">> createClient"); -#ifndef CONFIG_GATTC_ENABLE // Check that BLE GATTC is enabled in make menuconfig - ESP_LOGE(LOG_TAG, "BLE GATTC is not enabled - CONFIG_GATTC_ENABLE not defined"); - abort(); -#endif // CONFIG_GATTC_ENABLE - m_pClient = new BLEClient(); - ESP_LOGD(LOG_TAG, "<< createClient"); - return m_pClient; -} // createClient - - -/** - * @brief Create a new instance of a server. - * @return A new instance of the server. - */ -/* STATIC */ BLEServer* BLEDevice::createServer() { - ESP_LOGD(LOG_TAG, ">> createServer"); -#ifndef CONFIG_GATTS_ENABLE // Check that BLE GATTS is enabled in make menuconfig - ESP_LOGE(LOG_TAG, "BLE GATTS is not enabled - CONFIG_GATTS_ENABLE not defined"); - abort(); -#endif // CONFIG_GATTS_ENABLE - m_pServer = new BLEServer(); - m_pServer->createApp(0); - ESP_LOGD(LOG_TAG, "<< createServer"); - return m_pServer; -} // createServer - - -/** - * @brief Handle GATT server events. - * - * @param [in] event The event that has been newly received. - * @param [in] gatts_if The connection to the GATT interface. - * @param [in] param Parameters for the event. - */ -/* STATIC */ void BLEDevice::gattServerEventHandler( - esp_gatts_cb_event_t event, - esp_gatt_if_t gatts_if, - esp_ble_gatts_cb_param_t* param -) { - ESP_LOGD(LOG_TAG, "gattServerEventHandler [esp_gatt_if: %d] ... %s", - gatts_if, - BLEUtils::gattServerEventTypeToString(event).c_str()); - - BLEUtils::dumpGattServerEvent(event, gatts_if, param); - - switch(event) { - case ESP_GATTS_CONNECT_EVT: { - BLEDevice::m_localMTU = 23; -#ifdef CONFIG_BLE_SMP_ENABLE // Check that BLE SMP (security) is configured in make menuconfig - if(BLEDevice::m_securityLevel){ - esp_ble_set_encryption(param->connect.remote_bda, BLEDevice::m_securityLevel); - } -#endif // CONFIG_BLE_SMP_ENABLE - break; - } // ESP_GATTS_CONNECT_EVT - - case ESP_GATTS_MTU_EVT: { - BLEDevice::m_localMTU = param->mtu.mtu; - ESP_LOGI(LOG_TAG, "ESP_GATTS_MTU_EVT, MTU %d", BLEDevice::m_localMTU); - break; - } - default: { - break; - } - } // switch - - - if (BLEDevice::m_pServer != nullptr) { - BLEDevice::m_pServer->handleGATTServerEvent(event, gatts_if, param); - } -} // gattServerEventHandler - - -/** - * @brief Handle GATT client events. - * - * Handler for the GATT client events. - * - * @param [in] event - * @param [in] gattc_if - * @param [in] param - */ -/* STATIC */ void BLEDevice::gattClientEventHandler( - esp_gattc_cb_event_t event, - esp_gatt_if_t gattc_if, - esp_ble_gattc_cb_param_t* param) { - - ESP_LOGD(LOG_TAG, "gattClientEventHandler [esp_gatt_if: %d] ... %s", - gattc_if, BLEUtils::gattClientEventTypeToString(event).c_str()); - BLEUtils::dumpGattClientEvent(event, gattc_if, param); - - switch(event) { - case ESP_GATTC_CONNECT_EVT: { - if(BLEDevice::getMTU() != 23){ - esp_err_t errRc = esp_ble_gattc_send_mtu_req(gattc_if, param->connect.conn_id); - if (errRc != ESP_OK) { - ESP_LOGE(LOG_TAG, "esp_ble_gattc_send_mtu_req: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - } - } -#ifdef CONFIG_BLE_SMP_ENABLE // Check that BLE SMP (security) is configured in make menuconfig - if(BLEDevice::m_securityLevel){ - esp_ble_set_encryption(param->connect.remote_bda, BLEDevice::m_securityLevel); - } -#endif // CONFIG_BLE_SMP_ENABLE - break; - } // ESP_GATTC_CONNECT_EVT - - default: { - break; - } - } // switch - - - // If we have a client registered, call it. - if (BLEDevice::m_pClient != nullptr) { - BLEDevice::m_pClient->gattClientEventHandler(event, gattc_if, param); - } - -} // gattClientEventHandler - - -/** - * @brief Handle GAP events. - */ -/* STATIC */ void BLEDevice::gapEventHandler( - esp_gap_ble_cb_event_t event, - esp_ble_gap_cb_param_t *param) { - - BLEUtils::dumpGapEvent(event, param); - - switch(event) { - - case ESP_GAP_BLE_OOB_REQ_EVT: /* OOB request event */ - ESP_LOGI(LOG_TAG, "ESP_GAP_BLE_OOB_REQ_EVT"); - break; - case ESP_GAP_BLE_LOCAL_IR_EVT: /* BLE local IR event */ - ESP_LOGI(LOG_TAG, "ESP_GAP_BLE_LOCAL_IR_EVT"); - break; - case ESP_GAP_BLE_LOCAL_ER_EVT: /* BLE local ER event */ - ESP_LOGI(LOG_TAG, "ESP_GAP_BLE_LOCAL_ER_EVT"); - break; - case ESP_GAP_BLE_NC_REQ_EVT: - ESP_LOGI(LOG_TAG, "ESP_GAP_BLE_NC_REQ_EVT"); -#ifdef CONFIG_BLE_SMP_ENABLE // Check that BLE SMP (security) is configured in make menuconfig - if(BLEDevice::m_securityCallbacks!=nullptr){ - esp_ble_confirm_reply(param->ble_security.ble_req.bd_addr, BLEDevice::m_securityCallbacks->onConfirmPIN(param->ble_security.key_notif.passkey)); - } -#endif // CONFIG_BLE_SMP_ENABLE - break; - case ESP_GAP_BLE_PASSKEY_REQ_EVT: /* passkey request event */ - ESP_LOGI(LOG_TAG, "ESP_GAP_BLE_PASSKEY_REQ_EVT: "); - // esp_log_buffer_hex(LOG_TAG, m_remote_bda, sizeof(m_remote_bda)); -#ifdef CONFIG_BLE_SMP_ENABLE // Check that BLE SMP (security) is configured in make menuconfig - if(BLEDevice::m_securityCallbacks!=nullptr){ - esp_ble_passkey_reply(param->ble_security.ble_req.bd_addr, true, BLEDevice::m_securityCallbacks->onPassKeyRequest()); - } -#endif // CONFIG_BLE_SMP_ENABLE - break; - /* - * TODO should we add white/black list comparison? - */ - case ESP_GAP_BLE_SEC_REQ_EVT: - /* send the positive(true) security response to the peer device to accept the security request. - If not accept the security request, should sent the security response with negative(false) accept value*/ - ESP_LOGI(LOG_TAG, "ESP_GAP_BLE_SEC_REQ_EVT"); -#ifdef CONFIG_BLE_SMP_ENABLE // Check that BLE SMP (security) is configured in make menuconfig - if(BLEDevice::m_securityCallbacks!=nullptr){ - esp_ble_gap_security_rsp(param->ble_security.ble_req.bd_addr, BLEDevice::m_securityCallbacks->onSecurityRequest()); - } - else{ - esp_ble_gap_security_rsp(param->ble_security.ble_req.bd_addr, true); - } -#endif // CONFIG_BLE_SMP_ENABLE - break; - /* - * - */ - case ESP_GAP_BLE_PASSKEY_NOTIF_EVT: ///the app will receive this evt when the IO has Output capability and the peer device IO has Input capability. - ///show the passkey number to the user to input it in the peer deivce. - ESP_LOGI(LOG_TAG, "ESP_GAP_BLE_PASSKEY_NOTIF_EVT"); -#ifdef CONFIG_BLE_SMP_ENABLE // Check that BLE SMP (security) is configured in make menuconfig - if(BLEDevice::m_securityCallbacks!=nullptr){ - ESP_LOGI(LOG_TAG, "passKey = %d", param->ble_security.key_notif.passkey); - BLEDevice::m_securityCallbacks->onPassKeyNotify(param->ble_security.key_notif.passkey); - } -#endif // CONFIG_BLE_SMP_ENABLE - break; - case ESP_GAP_BLE_KEY_EVT: - //shows the ble key type info share with peer device to the user. - ESP_LOGI(LOG_TAG, "ESP_GAP_BLE_KEY_EVT"); -#ifdef CONFIG_BLE_SMP_ENABLE // Check that BLE SMP (security) is configured in make menuconfig - ESP_LOGI(LOG_TAG, "key type = %s", BLESecurity::esp_key_type_to_str(param->ble_security.ble_key.key_type)); -#endif // CONFIG_BLE_SMP_ENABLE - break; - case ESP_GAP_BLE_AUTH_CMPL_EVT: - ESP_LOGI(LOG_TAG, "ESP_GAP_BLE_AUTH_CMPL_EVT"); -#ifdef CONFIG_BLE_SMP_ENABLE // Check that BLE SMP (security) is configured in make menuconfig - if(BLEDevice::m_securityCallbacks!=nullptr){ - BLEDevice::m_securityCallbacks->onAuthenticationComplete(param->ble_security.auth_cmpl); - } -#endif // CONFIG_BLE_SMP_ENABLE - break; - default: { - break; - } - } // switch - - if (BLEDevice::m_pServer != nullptr) { - BLEDevice::m_pServer->handleGAPEvent(event, param); - } - - if (BLEDevice::m_pClient != nullptr) { - BLEDevice::m_pClient->handleGAPEvent(event, param); - } - - if (BLEDevice::m_pScan != nullptr) { - BLEDevice::getScan()->handleGAPEvent(event, param); - } - - /* - * Security events: - */ - - -} // gapEventHandler - - -/** - * @brief Get the BLE device address. - * @return The BLE device address. - */ -/* STATIC*/ BLEAddress BLEDevice::getAddress() { - const uint8_t* bdAddr = esp_bt_dev_get_address(); - esp_bd_addr_t addr; - memcpy(addr, bdAddr, sizeof(addr)); - return BLEAddress(addr); -} // getAddress - - -/** - * @brief Retrieve the Scan object that we use for scanning. - * @return The scanning object reference. This is a singleton object. The caller should not - * try and release/delete it. - */ -/* STATIC */ BLEScan* BLEDevice::getScan() { - //ESP_LOGD(LOG_TAG, ">> getScan"); - if (m_pScan == nullptr) { - m_pScan = new BLEScan(); - //ESP_LOGD(LOG_TAG, " - creating a new scan object"); - } - //ESP_LOGD(LOG_TAG, "<< getScan: Returning object at 0x%x", (uint32_t)m_pScan); - return m_pScan; -} // getScan - - -/** - * @brief Get the value of a characteristic of a service on a remote device. - * @param [in] bdAddress - * @param [in] serviceUUID - * @param [in] characteristicUUID - */ -/* STATIC */ std::string BLEDevice::getValue(BLEAddress bdAddress, BLEUUID serviceUUID, BLEUUID characteristicUUID) { - ESP_LOGD(LOG_TAG, ">> getValue: bdAddress: %s, serviceUUID: %s, characteristicUUID: %s", bdAddress.toString().c_str(), serviceUUID.toString().c_str(), characteristicUUID.toString().c_str()); - BLEClient *pClient = createClient(); - pClient->connect(bdAddress); - std::string ret = pClient->getValue(serviceUUID, characteristicUUID); - pClient->disconnect(); - ESP_LOGD(LOG_TAG, "<< getValue"); - return ret; -} // getValue - - -/** - * @brief Initialize the %BLE environment. - * @param deviceName The device name of the device. - */ -/* STATIC */ void BLEDevice::init(std::string deviceName) { - if(!initialized){ - initialized = true; // Set the initialization flag to ensure we are only initialized once. - - esp_err_t errRc = ESP_OK; -#ifdef ARDUINO_ARCH_ESP32 - if (!btStart()) { - errRc = ESP_FAIL; - return; - } -#else - errRc = ::nvs_flash_init(); - if (errRc != ESP_OK) { - ESP_LOGE(LOG_TAG, "nvs_flash_init: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return; - } - - esp_bt_controller_config_t bt_cfg = BT_CONTROLLER_INIT_CONFIG_DEFAULT(); - errRc = esp_bt_controller_init(&bt_cfg); - if (errRc != ESP_OK) { - ESP_LOGE(LOG_TAG, "esp_bt_controller_init: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return; - } - -#ifndef CLASSIC_BT_ENABLED - // esp_bt_controller_mem_release(ESP_BT_MODE_CLASSIC_BT); //FIXME waiting for response from esp-idf issue - errRc = esp_bt_controller_enable(ESP_BT_MODE_BLE); - //errRc = esp_bt_controller_enable(ESP_BT_MODE_BTDM); - if (errRc != ESP_OK) { - ESP_LOGE(LOG_TAG, "esp_bt_controller_enable: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return; - } -#else - errRc = esp_bt_controller_enable(ESP_BT_MODE_BTDM); - if (errRc != ESP_OK) { - ESP_LOGE(LOG_TAG, "esp_bt_controller_enable: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return; - } -#endif -#endif - - esp_bluedroid_status_t bt_state = esp_bluedroid_get_status(); - if (bt_state == ESP_BLUEDROID_STATUS_UNINITIALIZED){ - errRc = esp_bluedroid_init(); - if (errRc != ESP_OK) { - ESP_LOGE(LOG_TAG, "esp_bluedroid_init: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return; - } - } - - if (bt_state != ESP_BLUEDROID_STATUS_ENABLED){ - errRc = esp_bluedroid_enable(); - if (errRc != ESP_OK) { - ESP_LOGE(LOG_TAG, "esp_bluedroid_enable: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return; - } - } - - errRc = esp_ble_gap_register_callback(BLEDevice::gapEventHandler); - if (errRc != ESP_OK) { - ESP_LOGE(LOG_TAG, "esp_ble_gap_register_callback: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return; - } - -#ifdef CONFIG_GATTC_ENABLE // Check that BLE client is configured in make menuconfig - errRc = esp_ble_gattc_register_callback(BLEDevice::gattClientEventHandler); - if (errRc != ESP_OK) { - ESP_LOGE(LOG_TAG, "esp_ble_gattc_register_callback: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return; - } -#endif // CONFIG_GATTC_ENABLE - -#ifdef CONFIG_GATTS_ENABLE // Check that BLE server is configured in make menuconfig - errRc = esp_ble_gatts_register_callback(BLEDevice::gattServerEventHandler); - if (errRc != ESP_OK) { - ESP_LOGE(LOG_TAG, "esp_ble_gatts_register_callback: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return; - } -#endif // CONFIG_GATTS_ENABLE - - errRc = ::esp_ble_gap_set_device_name(deviceName.c_str()); - if (errRc != ESP_OK) { - ESP_LOGE(LOG_TAG, "esp_ble_gap_set_device_name: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return; - }; - -#ifdef CONFIG_BLE_SMP_ENABLE // Check that BLE SMP (security) is configured in make menuconfig - esp_ble_io_cap_t iocap = ESP_IO_CAP_NONE; - errRc = ::esp_ble_gap_set_security_param(ESP_BLE_SM_IOCAP_MODE, &iocap, sizeof(uint8_t)); - if (errRc != ESP_OK) { - ESP_LOGE(LOG_TAG, "esp_ble_gap_set_security_param: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return; - }; -#endif // CONFIG_BLE_SMP_ENABLE - } - vTaskDelay(200/portTICK_PERIOD_MS); // Delay for 200 msecs as a workaround to an apparent Arduino environment issue. -} // init - - -/** - * @brief Set the transmission power. - * The power level can be one of: - * * ESP_PWR_LVL_N14 - * * ESP_PWR_LVL_N11 - * * ESP_PWR_LVL_N8 - * * ESP_PWR_LVL_N5 - * * ESP_PWR_LVL_N2 - * * ESP_PWR_LVL_P1 - * * ESP_PWR_LVL_P4 - * * ESP_PWR_LVL_P7 - * @param [in] powerLevel. - */ -/* STATIC */ void BLEDevice::setPower(esp_power_level_t powerLevel) { - ESP_LOGD(LOG_TAG, ">> setPower: %d", powerLevel); - esp_err_t errRc = ::esp_ble_tx_power_set(ESP_BLE_PWR_TYPE_DEFAULT, powerLevel); - if (errRc != ESP_OK) { - ESP_LOGE(LOG_TAG, "esp_ble_tx_power_set: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - }; - ESP_LOGD(LOG_TAG, "<< setPower"); -} // setPower - - -/** - * @brief Set the value of a characteristic of a service on a remote device. - * @param [in] bdAddress - * @param [in] serviceUUID - * @param [in] characteristicUUID - */ -/* STATIC */ void BLEDevice::setValue(BLEAddress bdAddress, BLEUUID serviceUUID, BLEUUID characteristicUUID, std::string value) { - ESP_LOGD(LOG_TAG, ">> setValue: bdAddress: %s, serviceUUID: %s, characteristicUUID: %s", bdAddress.toString().c_str(), serviceUUID.toString().c_str(), characteristicUUID.toString().c_str()); - BLEClient *pClient = createClient(); - pClient->connect(bdAddress); - pClient->setValue(serviceUUID, characteristicUUID, value); - pClient->disconnect(); -} // setValue - - -/** - * @brief Return a string representation of the nature of this device. - * @return A string representation of the nature of this device. - */ -/* STATIC */ std::string BLEDevice::toString() { - std::ostringstream oss; - oss << "BD Address: " << getAddress().toString(); - return oss.str(); -} // toString - - -/** - * @brief Add an entry to the BLE white list. - * @param [in] address The address to add to the white list. - */ -void BLEDevice::whiteListAdd(BLEAddress address) { - ESP_LOGD(LOG_TAG, ">> whiteListAdd: %s", address.toString().c_str()); - esp_err_t errRc = esp_ble_gap_update_whitelist(true, *address.getNative()); // True to add an entry. - if (errRc != ESP_OK) { - ESP_LOGE(LOG_TAG, "esp_ble_gap_update_whitelist: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - } - ESP_LOGD(LOG_TAG, "<< whiteListAdd"); -} // whiteListAdd - - -/** - * @brief Remove an entry from the BLE white list. - * @param [in] address The address to remove from the white list. - */ -void BLEDevice::whiteListRemove(BLEAddress address) { - ESP_LOGD(LOG_TAG, ">> whiteListRemove: %s", address.toString().c_str()); - esp_err_t errRc = esp_ble_gap_update_whitelist(false, *address.getNative()); // False to remove an entry. - if (errRc != ESP_OK) { - ESP_LOGE(LOG_TAG, "esp_ble_gap_update_whitelist: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - } - ESP_LOGD(LOG_TAG, "<< whiteListRemove"); -} // whiteListRemove - -/* - * @brief Set encryption level that will be negotiated with peer device durng connection - * @param [in] level Requested encryption level - */ -void BLEDevice::setEncryptionLevel(esp_ble_sec_act_t level) { - BLEDevice::m_securityLevel = level; -} - -/* - * @brief Set callbacks that will be used to handle encryption negotiation events and authentication events - * @param [in] cllbacks Pointer to BLESecurityCallbacks class callback - */ -void BLEDevice::setSecurityCallbacks(BLESecurityCallbacks* callbacks) { - BLEDevice::m_securityCallbacks = callbacks; -} - -/* - * @brief Setup local mtu that will be used to negotiate mtu during request from client peer - * @param [in] mtu Value to set local mtu, should be larger than 23 and lower or equal to 517 - */ -esp_err_t BLEDevice::setMTU(uint16_t mtu) { - ESP_LOGD(LOG_TAG, ">> setLocalMTU: %d", mtu); - esp_err_t err = esp_ble_gatt_set_local_mtu(mtu); - if(err == ESP_OK){ - m_localMTU = mtu; - } else { - ESP_LOGE(LOG_TAG, "can't set local mtu value: %d", mtu); - } - ESP_LOGD(LOG_TAG, "<< setLocalMTU"); - return err; -} - -/* - * @brief Get local MTU value set during mtu request or default value - */ -uint16_t BLEDevice::getMTU() { - return m_localMTU; -} - -bool BLEDevice::getInitialized() { - return initialized; -} -#endif // CONFIG_BT_ENABLED diff --git a/lib/ESP32_BLE_Arduino/src/BLEDevice.h b/lib/ESP32_BLE_Arduino/src/BLEDevice.h deleted file mode 100644 index 7a1b833d..00000000 --- a/lib/ESP32_BLE_Arduino/src/BLEDevice.h +++ /dev/null @@ -1,74 +0,0 @@ -/* - * BLEDevice.h - * - * Created on: Mar 16, 2017 - * Author: kolban - */ - -#ifndef MAIN_BLEDevice_H_ -#define MAIN_BLEDevice_H_ -#include "sdkconfig.h" -#if defined(CONFIG_BT_ENABLED) -#include // ESP32 BLE -#include // ESP32 BLE -#include // Part of C++ STL -#include -#include - -#include "BLEServer.h" -#include "BLEClient.h" -#include "BLEUtils.h" -#include "BLEScan.h" -#include "BLEAddress.h" - -/** - * @brief %BLE functions. - */ -class BLEDevice { -public: - - static BLEClient* createClient(); // Create a new BLE client. - static BLEServer* createServer(); // Cretae a new BLE server. - static BLEAddress getAddress(); // Retrieve our own local BD address. - static BLEScan* getScan(); // Get the scan object - static std::string getValue(BLEAddress bdAddress, BLEUUID serviceUUID, BLEUUID characteristicUUID); // Get the value of a characteristic of a service on a server. - static void init(std::string deviceName); // Initialize the local BLE environment. - static void setPower(esp_power_level_t powerLevel); // Set our power level. - static void setValue(BLEAddress bdAddress, BLEUUID serviceUUID, BLEUUID characteristicUUID, std::string value); // Set the value of a characteristic on a service on a server. - static std::string toString(); // Return a string representation of our device. - static void whiteListAdd(BLEAddress address); // Add an entry to the BLE white list. - static void whiteListRemove(BLEAddress address); // Remove an entry from the BLE white list. - static void setEncryptionLevel(esp_ble_sec_act_t level); - static void setSecurityCallbacks(BLESecurityCallbacks* pCallbacks); - static esp_err_t setMTU(uint16_t mtu); - static uint16_t getMTU(); - static bool getInitialized(); // Returns the state of the device, is it initialized or not? - -private: - static BLEServer *m_pServer; - static BLEScan *m_pScan; - static BLEClient *m_pClient; - static esp_ble_sec_act_t m_securityLevel; - static BLESecurityCallbacks* m_securityCallbacks; - static uint16_t m_localMTU; - - static esp_gatt_if_t getGattcIF(); - - static void gattClientEventHandler( - esp_gattc_cb_event_t event, - esp_gatt_if_t gattc_if, - esp_ble_gattc_cb_param_t* param); - - static void gattServerEventHandler( - esp_gatts_cb_event_t event, - esp_gatt_if_t gatts_if, - esp_ble_gatts_cb_param_t* param); - - static void gapEventHandler( - esp_gap_ble_cb_event_t event, - esp_ble_gap_cb_param_t* param); - -}; // class BLE - -#endif // CONFIG_BT_ENABLED -#endif /* MAIN_BLEDevice_H_ */ diff --git a/lib/ESP32_BLE_Arduino/src/BLEExceptions.cpp b/lib/ESP32_BLE_Arduino/src/BLEExceptions.cpp deleted file mode 100644 index b6adfd82..00000000 --- a/lib/ESP32_BLE_Arduino/src/BLEExceptions.cpp +++ /dev/null @@ -1,9 +0,0 @@ -/* - * BLExceptions.cpp - * - * Created on: Nov 27, 2017 - * Author: kolban - */ - -#include "BLEExceptions.h" - diff --git a/lib/ESP32_BLE_Arduino/src/BLEExceptions.h b/lib/ESP32_BLE_Arduino/src/BLEExceptions.h deleted file mode 100644 index 369fcaf6..00000000 --- a/lib/ESP32_BLE_Arduino/src/BLEExceptions.h +++ /dev/null @@ -1,31 +0,0 @@ -/* - * BLExceptions.h - * - * Created on: Nov 27, 2017 - * Author: kolban - */ - -#ifndef COMPONENTS_CPP_UTILS_BLEEXCEPTIONS_H_ -#define COMPONENTS_CPP_UTILS_BLEEXCEPTIONS_H_ -#include "sdkconfig.h" - -#if CONFIG_CXX_EXCEPTIONS != 1 -#error "C++ exception handling must be enabled within make menuconfig. See Compiler Options > Enable C++ Exceptions." -#endif - -#include - - -class BLEDisconnectedException : public std::exception { - const char *what() const throw () { - return "BLE Disconnected"; - } -}; - -class BLEUuidNotFoundException : public std::exception { - const char *what() const throw () { - return "No such UUID"; - } -}; - -#endif /* COMPONENTS_CPP_UTILS_BLEEXCEPTIONS_H_ */ diff --git a/lib/ESP32_BLE_Arduino/src/BLEHIDDevice.cpp b/lib/ESP32_BLE_Arduino/src/BLEHIDDevice.cpp deleted file mode 100644 index 29376f3a..00000000 --- a/lib/ESP32_BLE_Arduino/src/BLEHIDDevice.cpp +++ /dev/null @@ -1,234 +0,0 @@ -/* - * BLEHIDDevice.cpp - * - * Created on: Jan 03, 2018 - * Author: chegewara - */ -#include "sdkconfig.h" -#if defined(CONFIG_BT_ENABLED) - -#include "BLEHIDDevice.h" -#include "BLE2904.h" - - -BLEHIDDevice::BLEHIDDevice(BLEServer* server) { - /* - * Here we create mandatory services described in bluetooth specification - */ - m_deviceInfoService = server->createService(BLEUUID((uint16_t) 0x180a)); - m_hidService = server->createService(BLEUUID((uint16_t) 0x1812), 40); - m_batteryService = server->createService(BLEUUID((uint16_t) 0x180f)); - - /* - * Mandatory characteristic for device info service - */ - m_pnpCharacteristic = m_deviceInfoService->createCharacteristic((uint16_t)0x2a50, BLECharacteristic::PROPERTY_READ); - - /* - * Mandatory characteristics for HID service - */ - m_hidInfoCharacteristic = m_hidService->createCharacteristic((uint16_t)0x2a4a, BLECharacteristic::PROPERTY_READ); - m_reportMapCharacteristic = m_hidService->createCharacteristic((uint16_t)0x2a4b, BLECharacteristic::PROPERTY_READ); - m_hidControlCharacteristic = m_hidService->createCharacteristic((uint16_t)0x2a4c, BLECharacteristic::PROPERTY_WRITE_NR); - m_protocolModeCharacteristic = m_hidService->createCharacteristic((uint16_t)0x2a4e, BLECharacteristic::PROPERTY_WRITE_NR | BLECharacteristic::PROPERTY_READ); - - /* - * Mandatory battery level characteristic with notification and presence descriptor - */ - BLE2904* batteryLevelDescriptor = new BLE2904(); - batteryLevelDescriptor->setFormat(BLE2904::FORMAT_UINT8); - batteryLevelDescriptor->setNamespace(1); - batteryLevelDescriptor->setUnit(0x27ad); - - m_batteryLevelCharacteristic = m_batteryService->createCharacteristic((uint16_t)0x2a19, BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_NOTIFY); - m_batteryLevelCharacteristic->addDescriptor(batteryLevelDescriptor); - m_batteryLevelCharacteristic->addDescriptor(new BLE2902()); - - /* - * This value is setup here because its default value in most usage cases, its very rare to use boot mode - * and we want to simplify library using as much as possible - */ - const uint8_t pMode[] = {0x01}; - protocolMode()->setValue((uint8_t*)pMode, 1); -} - -BLEHIDDevice::~BLEHIDDevice() { -} - -/* - * @brief - */ -void BLEHIDDevice::reportMap(uint8_t* map, uint16_t size) { - m_reportMapCharacteristic->setValue(map, size); -} - -/* - * @brief This function suppose to be called at the end, when we have created all characteristics we need to build HID service - */ -void BLEHIDDevice::startServices() { - m_deviceInfoService->start(); - m_hidService->start(); - m_batteryService->start(); -} - -/* - * @brief Create manufacturer characteristic (this characteristic is optional) - */ -BLECharacteristic* BLEHIDDevice::manufacturer() { - m_manufacturerCharacteristic = m_deviceInfoService->createCharacteristic((uint16_t)0x2a29, BLECharacteristic::PROPERTY_READ); - return m_manufacturerCharacteristic; -} - -/* - * @brief Set manufacturer name - * @param [in] name manufacturer name - */ -void BLEHIDDevice::manufacturer(std::string name) { - m_manufacturerCharacteristic->setValue(name); -} - -/* - * @brief - */ -void BLEHIDDevice::pnp(uint8_t sig, uint16_t vid, uint16_t pid, uint16_t version) { - uint8_t pnp[] = {sig, (uint8_t)(vid>>8), (uint8_t)vid, (uint8_t)(pid>>8), (uint8_t)pid, (uint8_t)(version>>8), (uint8_t)version}; - m_pnpCharacteristic->setValue(pnp, sizeof(pnp)); -} - -/* - * @brief - */ -void BLEHIDDevice::hidInfo(uint8_t country, uint8_t flags) { - uint8_t info[] = {0x11,0x1, country, flags}; - m_hidInfoCharacteristic->setValue(info, sizeof(info));; -} - -/* - * @brief Create input report characteristic that need to be saved as new characteristic object so can be further used - * @param [in] reportID input report ID, the same as in report map for input object related to created characteristic - * @return pointer to new input report characteristic - */ -BLECharacteristic* BLEHIDDevice::inputReport(uint8_t reportID) { - BLECharacteristic* inputReportCharacteristic = m_hidService->createCharacteristic((uint16_t)0x2a4d, BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_NOTIFY); - BLEDescriptor* inputReportDescriptor = new BLEDescriptor(BLEUUID((uint16_t)0x2908)); - - uint8_t desc1_val[] = {reportID, 0x01}; - inputReportDescriptor->setValue((uint8_t*)desc1_val, 2); - inputReportCharacteristic->addDescriptor(new BLE2902()); - inputReportCharacteristic->addDescriptor(inputReportDescriptor); - - return inputReportCharacteristic; -} - -/* - * @brief Create output report characteristic that need to be saved as new characteristic object so can be further used - * @param [in] reportID Output report ID, the same as in report map for output object related to created characteristic - * @return Pointer to new output report characteristic - */ -BLECharacteristic* BLEHIDDevice::outputReport(uint8_t reportID) { - BLECharacteristic* outputReportCharacteristic = m_hidService->createCharacteristic((uint16_t)0x2a4d, BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_WRITE | BLECharacteristic::PROPERTY_WRITE_NR); - BLEDescriptor* outputReportDescriptor = new BLEDescriptor(BLEUUID((uint16_t)0x2908)); - - uint8_t desc1_val[] = {reportID, 0x02}; - outputReportDescriptor->setValue((uint8_t*)desc1_val, 2); - outputReportCharacteristic->addDescriptor(outputReportDescriptor); - - return outputReportCharacteristic; -} - -/* - * @brief Create feature report characteristic that need to be saved as new characteristic object so can be further used - * @param [in] reportID Feature report ID, the same as in report map for feature object related to created characteristic - * @return Pointer to new feature report characteristic - */ -BLECharacteristic* BLEHIDDevice::featureReport(uint8_t reportID) { - BLECharacteristic* featureReportCharacteristic = m_hidService->createCharacteristic((uint16_t)0x2a4d, BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_WRITE); - BLEDescriptor* featureReportDescriptor = new BLEDescriptor(BLEUUID((uint16_t)0x2908)); - - uint8_t desc1_val[] = {reportID, 0x03}; - featureReportDescriptor->setValue((uint8_t*)desc1_val, 2); - featureReportCharacteristic->addDescriptor(featureReportDescriptor); - - return featureReportCharacteristic; -} - -/* - * @brief - */ -BLECharacteristic* BLEHIDDevice::bootInput() { - BLECharacteristic* bootInputCharacteristic = m_hidService->createCharacteristic((uint16_t)0x2a22, BLECharacteristic::PROPERTY_NOTIFY); - bootInputCharacteristic->addDescriptor(new BLE2902()); - - return bootInputCharacteristic; -} - -/* - * @brief - */ -BLECharacteristic* BLEHIDDevice::bootOutput() { - return m_hidService->createCharacteristic((uint16_t)0x2a32, BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_WRITE | BLECharacteristic::PROPERTY_WRITE_NR); -} - -/* - * @brief - */ -BLECharacteristic* BLEHIDDevice::hidControl() { - return m_hidControlCharacteristic; -} - -/* - * @brief - */ -BLECharacteristic* BLEHIDDevice::protocolMode() { - return m_protocolModeCharacteristic; -} - -void BLEHIDDevice::setBatteryLevel(uint8_t level) { - m_batteryLevelCharacteristic->setValue(&level, 1); -} -/* - * @brief Returns battery level characteristic - * @ return battery level characteristic - *//* -BLECharacteristic* BLEHIDDevice::batteryLevel() { - return m_batteryLevelCharacteristic; -} - - - -BLECharacteristic* BLEHIDDevice::reportMap() { - return m_reportMapCharacteristic; -} - -BLECharacteristic* BLEHIDDevice::pnp() { - return m_pnpCharacteristic; -} - - -BLECharacteristic* BLEHIDDevice::hidInfo() { - return m_hidInfoCharacteristic; -} -*/ -/* - * @brief - */ -BLEService* BLEHIDDevice::deviceInfo() { - return m_deviceInfoService; -} - -/* - * @brief - */ -BLEService* BLEHIDDevice::hidService() { - return m_hidService; -} - -/* - * @brief - */ -BLEService* BLEHIDDevice::batteryService() { - return m_batteryService; -} - -#endif // CONFIG_BT_ENABLED - diff --git a/lib/ESP32_BLE_Arduino/src/BLEHIDDevice.h b/lib/ESP32_BLE_Arduino/src/BLEHIDDevice.h deleted file mode 100644 index 319fd42a..00000000 --- a/lib/ESP32_BLE_Arduino/src/BLEHIDDevice.h +++ /dev/null @@ -1,75 +0,0 @@ -/* - * BLEHIDDevice.h - * - * Created on: Jan 03, 2018 - * Author: chegewara - */ - -#ifndef _BLEHIDDEVICE_H_ -#define _BLEHIDDEVICE_H_ - -#include "sdkconfig.h" -#if defined(CONFIG_BT_ENABLED) - -#include "BLECharacteristic.h" -#include "BLEService.h" -#include "BLEDescriptor.h" -#include "BLE2902.h" -#include "HIDTypes.h" - -#define GENERIC_HID 960 -#define HID_KEYBOARD 961 -#define HID_MOUSE 962 -#define HID_JOYSTICK 963 -#define HID_GAMEPAD 964 -#define HID_TABLET 965 -#define HID_CARD_READER 966 -#define HID_DIGITAL_PEN 967 -#define HID_BARCODE 968 - -class BLEHIDDevice { -public: - BLEHIDDevice(BLEServer*); - virtual ~BLEHIDDevice(); - - void reportMap(uint8_t* map, uint16_t); - void startServices(); - - BLEService* deviceInfo(); - BLEService* hidService(); - BLEService* batteryService(); - - BLECharacteristic* manufacturer(); - void manufacturer(std::string name); - //BLECharacteristic* pnp(); - void pnp(uint8_t sig, uint16_t vid, uint16_t pid, uint16_t version); - //BLECharacteristic* hidInfo(); - void hidInfo(uint8_t country, uint8_t flags); - //BLECharacteristic* batteryLevel(); - void setBatteryLevel(uint8_t level); - - - //BLECharacteristic* reportMap(); - BLECharacteristic* hidControl(); - BLECharacteristic* inputReport(uint8_t reportID); - BLECharacteristic* outputReport(uint8_t reportID); - BLECharacteristic* featureReport(uint8_t reportID); - BLECharacteristic* protocolMode(); - BLECharacteristic* bootInput(); - BLECharacteristic* bootOutput(); - -private: - BLEService* m_deviceInfoService; //0x180a - BLEService* m_hidService; //0x1812 - BLEService* m_batteryService = 0; //0x180f - - BLECharacteristic* m_manufacturerCharacteristic; //0x2a29 - BLECharacteristic* m_pnpCharacteristic; //0x2a50 - BLECharacteristic* m_hidInfoCharacteristic; //0x2a4a - BLECharacteristic* m_reportMapCharacteristic; //0x2a4b - BLECharacteristic* m_hidControlCharacteristic; //0x2a4c - BLECharacteristic* m_protocolModeCharacteristic; //0x2a4e - BLECharacteristic* m_batteryLevelCharacteristic; //0x2a19 -}; -#endif // CONFIG_BT_ENABLED -#endif /* _BLEHIDDEVICE_H_ */ diff --git a/lib/ESP32_BLE_Arduino/src/BLERemoteCharacteristic.cpp b/lib/ESP32_BLE_Arduino/src/BLERemoteCharacteristic.cpp deleted file mode 100644 index d9c64c91..00000000 --- a/lib/ESP32_BLE_Arduino/src/BLERemoteCharacteristic.cpp +++ /dev/null @@ -1,606 +0,0 @@ -/* - * BLERemoteCharacteristic.cpp - * - * Created on: Jul 8, 2017 - * Author: kolban - */ - -#include "BLERemoteCharacteristic.h" - -#include "sdkconfig.h" -#if defined(CONFIG_BT_ENABLED) - -#include -#include -#include - -#include -#include "BLEExceptions.h" -#include "BLEUtils.h" -#include "GeneralUtils.h" -#include "BLERemoteDescriptor.h" -#ifdef ARDUINO_ARCH_ESP32 -#include "esp32-hal-log.h" -#endif - - -static const char* LOG_TAG = "BLERemoteCharacteristic"; // The logging tag for this class. - -/** - * @brief Constructor. - * @param [in] handle The BLE server side handle of this characteristic. - * @param [in] uuid The UUID of this characteristic. - * @param [in] charProp The properties of this characteristic. - * @param [in] pRemoteService A reference to the remote service to which this remote characteristic pertains. - */ -BLERemoteCharacteristic::BLERemoteCharacteristic( - uint16_t handle, - BLEUUID uuid, - esp_gatt_char_prop_t charProp, - BLERemoteService* pRemoteService) { - ESP_LOGD(LOG_TAG, ">> BLERemoteCharacteristic: handle: %d 0x%d, uuid: %s", handle, handle, uuid.toString().c_str()); - m_handle = handle; - m_uuid = uuid; - m_charProp = charProp; - m_pRemoteService = pRemoteService; - m_notifyCallback = nullptr; - - retrieveDescriptors(); // Get the descriptors for this characteristic - ESP_LOGD(LOG_TAG, "<< BLERemoteCharacteristic"); -} // BLERemoteCharacteristic - - -/** - *@brief Destructor. - */ -BLERemoteCharacteristic::~BLERemoteCharacteristic() { - removeDescriptors(); // Release resources for any descriptor information we may have allocated. -} // ~BLERemoteCharacteristic - - -/** - * @brief Does the characteristic support broadcasting? - * @return True if the characteristic supports broadcasting. - */ -bool BLERemoteCharacteristic::canBroadcast() { - return (m_charProp & ESP_GATT_CHAR_PROP_BIT_BROADCAST) != 0; -} // canBroadcast - - -/** - * @brief Does the characteristic support indications? - * @return True if the characteristic supports indications. - */ -bool BLERemoteCharacteristic::canIndicate() { - return (m_charProp & ESP_GATT_CHAR_PROP_BIT_INDICATE) != 0; -} // canIndicate - - -/** - * @brief Does the characteristic support notifications? - * @return True if the characteristic supports notifications. - */ -bool BLERemoteCharacteristic::canNotify() { - return (m_charProp & ESP_GATT_CHAR_PROP_BIT_NOTIFY) != 0; -} // canNotify - - -/** - * @brief Does the characteristic support reading? - * @return True if the characteristic supports reading. - */ -bool BLERemoteCharacteristic::canRead() { - return (m_charProp & ESP_GATT_CHAR_PROP_BIT_READ) != 0; -} // canRead - - -/** - * @brief Does the characteristic support writing? - * @return True if the characteristic supports writing. - */ -bool BLERemoteCharacteristic::canWrite() { - return (m_charProp & ESP_GATT_CHAR_PROP_BIT_WRITE) != 0; -} // canWrite - - -/** - * @brief Does the characteristic support writing with no response? - * @return True if the characteristic supports writing with no response. - */ -bool BLERemoteCharacteristic::canWriteNoResponse() { - return (m_charProp & ESP_GATT_CHAR_PROP_BIT_WRITE_NR) != 0; -} // canWriteNoResponse - - -/* -static bool compareSrvcId(esp_gatt_srvc_id_t id1, esp_gatt_srvc_id_t id2) { - if (id1.id.inst_id != id2.id.inst_id) { - return false; - } - if (!BLEUUID(id1.id.uuid).equals(BLEUUID(id2.id.uuid))) { - return false; - } - return true; -} // compareSrvcId -*/ - -/* -static bool compareGattId(esp_gatt_id_t id1, esp_gatt_id_t id2) { - if (id1.inst_id != id2.inst_id) { - return false; - } - if (!BLEUUID(id1.uuid).equals(BLEUUID(id2.uuid))) { - return false; - } - return true; -} // compareCharId -*/ - - -/** - * @brief Handle GATT Client events. - * When an event arrives for a GATT client we give this characteristic the opportunity to - * take a look at it to see if there is interest in it. - * @param [in] event The type of event. - * @param [in] gattc_if The interface on which the event was received. - * @param [in] evtParam Payload data for the event. - * @returns N/A - */ -void BLERemoteCharacteristic::gattClientEventHandler( - esp_gattc_cb_event_t event, - esp_gatt_if_t gattc_if, - esp_ble_gattc_cb_param_t* evtParam) { - switch(event) { - // - // ESP_GATTC_NOTIFY_EVT - // - // notify - // - uint16_t conn_id - The connection identifier of the server. - // - esp_bd_addr_t remote_bda - The device address of the BLE server. - // - uint16_t handle - The handle of the characteristic for which the event is being received. - // - uint16_t value_len - The length of the received data. - // - uint8_t* value - The received data. - // - bool is_notify - True if this is a notify, false if it is an indicate. - // - // We have received a notification event which means that the server wishes us to know about a notification - // piece of data. What we must now do is find the characteristic with the associated handle and then - // invoke its notification callback (if it has one). - // - case ESP_GATTC_NOTIFY_EVT: { - if (evtParam->notify.handle != getHandle()) { - break; - } - if (m_notifyCallback != nullptr) { - ESP_LOGD(LOG_TAG, "Invoking callback for notification on characteristic %s", toString().c_str()); - m_notifyCallback( - this, - evtParam->notify.value, - evtParam->notify.value_len, - evtParam->notify.is_notify - ); - } // End we have a callback function ... - break; - } // ESP_GATTC_NOTIFY_EVT - - - // - // ESP_GATTC_READ_CHAR_EVT - // This event indicates that the server has responded to the read request. - // - // read: - // - esp_gatt_status_t status - // - uint16_t conn_id - // - uint16_t handle - // - uint8_t* value - // - uint16_t value_len - // - case ESP_GATTC_READ_CHAR_EVT: { - // If this event is not for us, then nothing further to do. - if (evtParam->read.handle != getHandle()) { - break; - } - - // At this point, we have determined that the event is for us, so now we save the value - // and unlock the semaphore to ensure that the requestor of the data can continue. - if (evtParam->read.status == ESP_GATT_OK) { - m_value = std::string((char*)evtParam->read.value, evtParam->read.value_len); - } else { - m_value = ""; - } - - m_semaphoreReadCharEvt.give(); - break; - } // ESP_GATTC_READ_CHAR_EVT - - - // - // ESP_GATTC_REG_FOR_NOTIFY_EVT - // - // reg_for_notify: - // - esp_gatt_status_t status - // - uint16_t handle - // - case ESP_GATTC_REG_FOR_NOTIFY_EVT: { - // If the request is not for this BLERemoteCharacteristic then move on to the next. - if (evtParam->reg_for_notify.handle != getHandle()) { - break; - } - - // We have processed the notify registration and can unlock the semaphore. - m_semaphoreRegForNotifyEvt.give(); - break; - } // ESP_GATTC_REG_FOR_NOTIFY_EVT - - - // - // ESP_GATTC_UNREG_FOR_NOTIFY_EVT - // - // unreg_for_notify: - // - esp_gatt_status_t status - // - uint16_t handle - // - case ESP_GATTC_UNREG_FOR_NOTIFY_EVT: { - if (evtParam->unreg_for_notify.handle != getHandle()) { - break; - } - // We have processed the notify un-registration and can unlock the semaphore. - m_semaphoreRegForNotifyEvt.give(); - break; - } // ESP_GATTC_UNREG_FOR_NOTIFY_EVT: - - - // - // ESP_GATTC_WRITE_CHAR_EVT - // - // write: - // - esp_gatt_status_t status - // - uint16_t conn_id - // - uint16_t handle - // - case ESP_GATTC_WRITE_CHAR_EVT: { - // Determine if this event is for us and, if not, pass onwards. - if (evtParam->write.handle != getHandle()) { - break; - } - - // There is nothing further we need to do here. This is merely an indication - // that the write has completed and we can unlock the caller. - m_semaphoreWriteCharEvt.give(); - break; - } // ESP_GATTC_WRITE_CHAR_EVT - - - default: { - break; - } - } // End switch -}; // gattClientEventHandler - - -/** - * @brief Populate the descriptors (if any) for this characteristic. - */ -void BLERemoteCharacteristic::retrieveDescriptors() { - ESP_LOGD(LOG_TAG, ">> retrieveDescriptors() for characteristic: %s", getUUID().toString().c_str()); - - removeDescriptors(); // Remove any existing descriptors. - - // Loop over each of the descriptors within the service associated with this characteristic. - // For each descriptor we find, create a BLERemoteDescriptor instance. - uint16_t offset = 0; - esp_gattc_descr_elem_t result; - while(1) { - uint16_t count = 1; - esp_gatt_status_t status = ::esp_ble_gattc_get_all_descr( - getRemoteService()->getClient()->getGattcIf(), - getRemoteService()->getClient()->getConnId(), - getHandle(), - &result, - &count, - offset - ); - - if (status == ESP_GATT_INVALID_OFFSET) { // We have reached the end of the entries. - break; - } - - if (status != ESP_GATT_OK) { - ESP_LOGE(LOG_TAG, "esp_ble_gattc_get_all_descr: %s", BLEUtils::gattStatusToString(status).c_str()); - break; - } - - if (count == 0) { - break; - } - ESP_LOGE(LOG_TAG, ""); - ESP_LOGD(LOG_TAG, "Found a descriptor: Handle: %d, UUID: %s", result.handle, BLEUUID(result.uuid).toString().c_str()); - - // We now have a new characteristic ... let us add that to our set of known characteristics - BLERemoteDescriptor *pNewRemoteDescriptor = new BLERemoteDescriptor( - result.handle, - BLEUUID(result.uuid), - this - ); - - m_descriptorMap.insert(std::pair(pNewRemoteDescriptor->getUUID().toString(), pNewRemoteDescriptor)); - - offset++; - } // while true - //m_haveCharacteristics = true; // Remember that we have received the characteristics. - ESP_LOGD(LOG_TAG, "<< retrieveDescriptors(): Found %d descriptors.", offset); -} // getDescriptors - - -/** - * @brief Retrieve the map of descriptors keyed by UUID. - */ -std::map* BLERemoteCharacteristic::getDescriptors() { - return &m_descriptorMap; -} // getDescriptors - - -/** - * @brief Get the handle for this characteristic. - * @return The handle for this characteristic. - */ -uint16_t BLERemoteCharacteristic::getHandle() { - //ESP_LOGD(LOG_TAG, ">> getHandle: Characteristic: %s", getUUID().toString().c_str()); - //ESP_LOGD(LOG_TAG, "<< getHandle: %d 0x%.2x", m_handle, m_handle); - return m_handle; -} // getHandle - - -/** - * @brief Get the descriptor instance with the given UUID that belongs to this characteristic. - * @param [in] uuid The UUID of the descriptor to find. - * @return The Remote descriptor (if present) or null if not present. - */ -BLERemoteDescriptor* BLERemoteCharacteristic::getDescriptor(BLEUUID uuid) { - ESP_LOGD(LOG_TAG, ">> getDescriptor: uuid: %s", uuid.toString().c_str()); - std::string v = uuid.toString(); - for (auto &myPair : m_descriptorMap) { - if (myPair.first == v) { - ESP_LOGD(LOG_TAG, "<< getDescriptor: found"); - return myPair.second; - } - } - ESP_LOGD(LOG_TAG, "<< getDescriptor: Not found"); - return nullptr; -} // getDescriptor - - -/** - * @brief Get the remote service associated with this characteristic. - * @return The remote service associated with this characteristic. - */ -BLERemoteService* BLERemoteCharacteristic::getRemoteService() { - return m_pRemoteService; -} // getRemoteService - - -/** - * @brief Get the UUID for this characteristic. - * @return The UUID for this characteristic. - */ -BLEUUID BLERemoteCharacteristic::getUUID() { - return m_uuid; -} // getUUID - - -/** - * @brief Read an unsigned 16 bit value - * @return The unsigned 16 bit value. - */ -uint16_t BLERemoteCharacteristic::readUInt16(void) { - std::string value = readValue(); - if (value.length() >= 2) { - return *(uint16_t*)(value.data()); - } - return 0; -} // readUInt16 - - -/** - * @brief Read an unsigned 32 bit value. - * @return the unsigned 32 bit value. - */ -uint32_t BLERemoteCharacteristic::readUInt32(void) { - std::string value = readValue(); - if (value.length() >= 4) { - return *(uint32_t*)(value.data()); - } - return 0; -} // readUInt32 - - -/** - * @brief Read a byte value - * @return The value as a byte - */ -uint8_t BLERemoteCharacteristic::readUInt8(void) { - std::string value = readValue(); - if (value.length() >= 1) { - return (uint8_t)value[0]; - } - return 0; -} // readUInt8 - - -/** - * @brief Read the value of the remote characteristic. - * @return The value of the remote characteristic. - */ -std::string BLERemoteCharacteristic::readValue() { - ESP_LOGD(LOG_TAG, ">> readValue(): uuid: %s, handle: %d 0x%.2x", getUUID().toString().c_str(), getHandle(), getHandle()); - - // Check to see that we are connected. - if (!getRemoteService()->getClient()->isConnected()) { - ESP_LOGE(LOG_TAG, "Disconnected"); - throw BLEDisconnectedException(); - } - - m_semaphoreReadCharEvt.take("readValue"); - - // Ask the BLE subsystem to retrieve the value for the remote hosted characteristic. - // This is an asynchronous request which means that we must block waiting for the response - // to become available. - esp_err_t errRc = ::esp_ble_gattc_read_char( - m_pRemoteService->getClient()->getGattcIf(), - m_pRemoteService->getClient()->getConnId(), // The connection ID to the BLE server - getHandle(), // The handle of this characteristic - ESP_GATT_AUTH_REQ_NONE); // Security - - if (errRc != ESP_OK) { - ESP_LOGE(LOG_TAG, "esp_ble_gattc_read_char: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return ""; - } - - // Block waiting for the event that indicates that the read has completed. When it has, the std::string found - // in m_value will contain our data. - m_semaphoreReadCharEvt.wait("readValue"); - - ESP_LOGD(LOG_TAG, "<< readValue(): length: %d", m_value.length()); - return m_value; -} // readValue - - -/** - * @brief Register for notifications. - * @param [in] notifyCallback A callback to be invoked for a notification. If NULL is provided then we are - * unregistering a notification. - * @return N/A. - */ -void BLERemoteCharacteristic::registerForNotify( - void (*notifyCallback)( - BLERemoteCharacteristic* pBLERemoteCharacteristic, - uint8_t* pData, - size_t length, - bool isNotify)) { - ESP_LOGD(LOG_TAG, ">> registerForNotify(): %s", toString().c_str()); - - m_notifyCallback = notifyCallback; // Save the notification callback. - - m_semaphoreRegForNotifyEvt.take("registerForNotify"); - - if (notifyCallback != nullptr) { // If we have a callback function, then this is a registration. - esp_err_t errRc = ::esp_ble_gattc_register_for_notify( - m_pRemoteService->getClient()->getGattcIf(), - *m_pRemoteService->getClient()->getPeerAddress().getNative(), - getHandle() - ); - - if (errRc != ESP_OK) { - ESP_LOGE(LOG_TAG, "esp_ble_gattc_register_for_notify: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - } - } // End Register - else { // If we weren't passed a callback function, then this is an unregistration. - esp_err_t errRc = ::esp_ble_gattc_unregister_for_notify( - m_pRemoteService->getClient()->getGattcIf(), - *m_pRemoteService->getClient()->getPeerAddress().getNative(), - getHandle() - ); - - if (errRc != ESP_OK) { - ESP_LOGE(LOG_TAG, "esp_ble_gattc_unregister_for_notify: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - } - } // End Unregister - - m_semaphoreRegForNotifyEvt.wait("registerForNotify"); - - ESP_LOGD(LOG_TAG, "<< registerForNotify()"); -} // registerForNotify - - -/** - * @brief Delete the descriptors in the descriptor map. - * We maintain a map called m_descriptorMap that contains pointers to BLERemoteDescriptors - * object references. Since we allocated these in this class, we are also responsible for deleteing - * them. This method does just that. - * @return N/A. - */ -void BLERemoteCharacteristic::removeDescriptors() { - // Iterate through all the descriptors releasing their storage and erasing them from the map. - for (auto &myPair : m_descriptorMap) { - m_descriptorMap.erase(myPair.first); - delete myPair.second; - } - m_descriptorMap.clear(); // Technically not neeeded, but just to be sure. -} // removeCharacteristics - - -/** - * @brief Convert a BLERemoteCharacteristic to a string representation; - * @return a String representation. - */ -std::string BLERemoteCharacteristic::toString() { - std::ostringstream ss; - ss << "Characteristic: uuid: " << m_uuid.toString() << - ", handle: " << getHandle() << " 0x" << std::hex << getHandle() << - ", props: " << BLEUtils::characteristicPropertiesToString(m_charProp); - return ss.str(); -} // toString - - -/** - * @brief Write the new value for the characteristic. - * @param [in] newValue The new value to write. - * @param [in] response Do we expect a response? - * @return N/A. - */ -void BLERemoteCharacteristic::writeValue(std::string newValue, bool response) { - ESP_LOGD(LOG_TAG, ">> writeValue(), length: %d", newValue.length()); - - // Check to see that we are connected. - if (!getRemoteService()->getClient()->isConnected()) { - ESP_LOGE(LOG_TAG, "Disconnected"); - throw BLEDisconnectedException(); - } - - m_semaphoreWriteCharEvt.take("writeValue"); - - // Invoke the ESP-IDF API to perform the write. - esp_err_t errRc = ::esp_ble_gattc_write_char( - m_pRemoteService->getClient()->getGattcIf(), - m_pRemoteService->getClient()->getConnId(), - getHandle(), - newValue.length(), - (uint8_t*)newValue.data(), - response?ESP_GATT_WRITE_TYPE_RSP:ESP_GATT_WRITE_TYPE_NO_RSP, - ESP_GATT_AUTH_REQ_NONE - ); - - if (errRc != ESP_OK) { - ESP_LOGE(LOG_TAG, "esp_ble_gattc_write_char: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return; - } - - m_semaphoreWriteCharEvt.wait("writeValue"); - - ESP_LOGD(LOG_TAG, "<< writeValue"); -} // writeValue - - -/** - * @brief Write the new value for the characteristic. - * - * This is a convenience function. Many BLE characteristics are a single byte of data. - * @param [in] newValue The new byte value to write. - * @param [in] response Whether we require a response from the write. - * @return N/A. - */ -void BLERemoteCharacteristic::writeValue(uint8_t newValue, bool response) { - writeValue(std::string(reinterpret_cast(&newValue), 1), response); -} // writeValue - - -/** - * @brief Write the new value for the characteristic from a data buffer. - * @param [in] data A pointer to a data buffer. - * @param [in] length The length of the data in the data buffer. - * @param [in] response Whether we require a response from the write. - */ -void BLERemoteCharacteristic::writeValue(uint8_t* data, size_t length, bool response) { - writeValue(std::string((char *)data, length), response); -} // writeValue - -#endif /* CONFIG_BT_ENABLED */ diff --git a/lib/ESP32_BLE_Arduino/src/BLERemoteCharacteristic.h b/lib/ESP32_BLE_Arduino/src/BLERemoteCharacteristic.h deleted file mode 100644 index 6f23f497..00000000 --- a/lib/ESP32_BLE_Arduino/src/BLERemoteCharacteristic.h +++ /dev/null @@ -1,85 +0,0 @@ -/* - * BLERemoteCharacteristic.h - * - * Created on: Jul 8, 2017 - * Author: kolban - */ - -#ifndef COMPONENTS_CPP_UTILS_BLEREMOTECHARACTERISTIC_H_ -#define COMPONENTS_CPP_UTILS_BLEREMOTECHARACTERISTIC_H_ -#include "sdkconfig.h" -#if defined(CONFIG_BT_ENABLED) - -#include - -#include - -#include "BLERemoteService.h" -#include "BLERemoteDescriptor.h" -#include "BLEUUID.h" -#include "FreeRTOS.h" - -class BLERemoteService; -class BLERemoteDescriptor; - -/** - * @brief A model of a remote %BLE characteristic. - */ -class BLERemoteCharacteristic { -public: - ~BLERemoteCharacteristic(); - - // Public member functions - bool canBroadcast(); - bool canIndicate(); - bool canNotify(); - bool canRead(); - bool canWrite(); - bool canWriteNoResponse(); - BLERemoteDescriptor* getDescriptor(BLEUUID uuid); - std::map* getDescriptors(); - uint16_t getHandle(); - BLEUUID getUUID(); - std::string readValue(void); - uint8_t readUInt8(void); - uint16_t readUInt16(void); - uint32_t readUInt32(void); - void registerForNotify(void (*notifyCallback)(BLERemoteCharacteristic* pBLERemoteCharacteristic, uint8_t* pData, size_t length, bool isNotify)); - void writeValue(uint8_t* data, size_t length, bool response = false); - void writeValue(std::string newValue, bool response = false); - void writeValue(uint8_t newValue, bool response = false); - std::string toString(void); - -private: - BLERemoteCharacteristic(uint16_t handle, BLEUUID uuid, esp_gatt_char_prop_t charProp, BLERemoteService* pRemoteService); - friend class BLEClient; - friend class BLERemoteService; - friend class BLERemoteDescriptor; - - // Private member functions - void gattClientEventHandler( - esp_gattc_cb_event_t event, - esp_gatt_if_t gattc_if, - esp_ble_gattc_cb_param_t* evtParam); - - - BLERemoteService* getRemoteService(); - void removeDescriptors(); - void retrieveDescriptors(); - - // Private properties - BLEUUID m_uuid; - esp_gatt_char_prop_t m_charProp; - uint16_t m_handle; - BLERemoteService* m_pRemoteService; - FreeRTOS::Semaphore m_semaphoreReadCharEvt = FreeRTOS::Semaphore("ReadCharEvt"); - FreeRTOS::Semaphore m_semaphoreRegForNotifyEvt = FreeRTOS::Semaphore("RegForNotifyEvt"); - FreeRTOS::Semaphore m_semaphoreWriteCharEvt = FreeRTOS::Semaphore("WriteCharEvt"); - std::string m_value; - void (*m_notifyCallback)(BLERemoteCharacteristic* pBLERemoteCharacteristic, uint8_t* pData, size_t length, bool isNotify); - - // We maintain a map of descriptors owned by this characteristic keyed by a string representation of the UUID. - std::map m_descriptorMap; -}; // BLERemoteCharacteristic -#endif /* CONFIG_BT_ENABLED */ -#endif /* COMPONENTS_CPP_UTILS_BLEREMOTECHARACTERISTIC_H_ */ diff --git a/lib/ESP32_BLE_Arduino/src/BLERemoteDescriptor.cpp b/lib/ESP32_BLE_Arduino/src/BLERemoteDescriptor.cpp deleted file mode 100644 index 4d14ba80..00000000 --- a/lib/ESP32_BLE_Arduino/src/BLERemoteDescriptor.cpp +++ /dev/null @@ -1,185 +0,0 @@ -/* - * BLERemoteDescriptor.cpp - * - * Created on: Jul 8, 2017 - * Author: kolban - */ -#include "sdkconfig.h" -#if defined(CONFIG_BT_ENABLED) -#include -#include "BLERemoteDescriptor.h" -#include "GeneralUtils.h" -#include -#ifdef ARDUINO_ARCH_ESP32 -#include "esp32-hal-log.h" -#endif - -static const char* LOG_TAG = "BLERemoteDescriptor"; - - -BLERemoteDescriptor::BLERemoteDescriptor( - uint16_t handle, - BLEUUID uuid, - BLERemoteCharacteristic* pRemoteCharacteristic) { - - m_handle = handle; - m_uuid = uuid; - m_pRemoteCharacteristic = pRemoteCharacteristic; -} - - -/** - * @brief Retrieve the handle associated with this remote descriptor. - * @return The handle associated with this remote descriptor. - */ -uint16_t BLERemoteDescriptor::getHandle() { - return m_handle; -} // getHandle - - -/** - * @brief Get the characteristic that owns this descriptor. - * @return The characteristic that owns this descriptor. - */ -BLERemoteCharacteristic* BLERemoteDescriptor::getRemoteCharacteristic() { - return m_pRemoteCharacteristic; -} // getRemoteCharacteristic - - -/** - * @brief Retrieve the UUID associated this remote descriptor. - * @return The UUID associated this remote descriptor. - */ -BLEUUID BLERemoteDescriptor::getUUID() { - return m_uuid; -} // getUUID - - -std::string BLERemoteDescriptor::readValue(void) { - ESP_LOGD(LOG_TAG, ">> readValue: %s", toString().c_str()); - - // Check to see that we are connected. - if (!getRemoteCharacteristic()->getRemoteService()->getClient()->isConnected()) { - ESP_LOGE(LOG_TAG, "Disconnected"); - throw BLEDisconnectedException(); - } - - m_semaphoreReadDescrEvt.take("readValue"); - - // Ask the BLE subsystem to retrieve the value for the remote hosted characteristic. - esp_err_t errRc = ::esp_ble_gattc_read_char_descr( - m_pRemoteCharacteristic->getRemoteService()->getClient()->getGattcIf(), - m_pRemoteCharacteristic->getRemoteService()->getClient()->getConnId(), // The connection ID to the BLE server - getHandle(), // The handle of this characteristic - ESP_GATT_AUTH_REQ_NONE); // Security - - if (errRc != ESP_OK) { - ESP_LOGE(LOG_TAG, "esp_ble_gattc_read_char: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return ""; - } - - // Block waiting for the event that indicates that the read has completed. When it has, the std::string found - // in m_value will contain our data. - m_semaphoreReadDescrEvt.wait("readValue"); - - ESP_LOGD(LOG_TAG, "<< readValue(): length: %d", m_value.length()); - return m_value; -} // readValue - - -uint8_t BLERemoteDescriptor::readUInt8(void) { - std::string value = readValue(); - if (value.length() >= 1) { - return (uint8_t)value[0]; - } - return 0; -} // readUInt8 - - -uint16_t BLERemoteDescriptor::readUInt16(void) { - std::string value = readValue(); - if (value.length() >= 2) { - return *(uint16_t*)(value.data()); - } - return 0; -} // readUInt16 - - -uint32_t BLERemoteDescriptor::readUInt32(void) { - std::string value = readValue(); - if (value.length() >= 4) { - return *(uint32_t*)(value.data()); - } - return 0; -} // readUInt32 - - -/** - * @brief Return a string representation of this BLE Remote Descriptor. - * @retun A string representation of this BLE Remote Descriptor. - */ -std::string BLERemoteDescriptor::toString(void) { - std::stringstream ss; - ss << "handle: " << getHandle() << ", uuid: " << getUUID().toString(); - return ss.str(); -} // toString - - -/** - * @brief Write data to the BLE Remote Descriptor. - * @param [in] data The data to send to the remote descriptor. - * @param [in] length The length of the data to send. - * @param [in] response True if we expect a response. - */ -void BLERemoteDescriptor::writeValue( - uint8_t* data, - size_t length, - bool response) { - ESP_LOGD(LOG_TAG, ">> writeValue: %s", toString().c_str()); - // Check to see that we are connected. - if (!getRemoteCharacteristic()->getRemoteService()->getClient()->isConnected()) { - ESP_LOGE(LOG_TAG, "Disconnected"); - throw BLEDisconnectedException(); - } - - esp_err_t errRc = ::esp_ble_gattc_write_char_descr( - m_pRemoteCharacteristic->getRemoteService()->getClient()->getGattcIf(), - m_pRemoteCharacteristic->getRemoteService()->getClient()->getConnId(), - getHandle(), - length, // Data length - data, // Data - ESP_GATT_WRITE_TYPE_NO_RSP, - ESP_GATT_AUTH_REQ_NONE - ); - if (errRc != ESP_OK) { - ESP_LOGE(LOG_TAG, "esp_ble_gattc_write_char_descr: %d", errRc); - } - ESP_LOGD(LOG_TAG, "<< writeValue"); -} // writeValue - - -/** - * @brief Write data represented as a string to the BLE Remote Descriptor. - * @param [in] newValue The data to send to the remote descriptor. - * @param [in] response True if we expect a response. - */ -void BLERemoteDescriptor::writeValue( - std::string newValue, - bool response) { - writeValue(newValue.data(), newValue.length()); -} // writeValue - - -/** - * @brief Write a byte value to the Descriptor. - * @param [in] The single byte to write. - * @param [in] True if we expect a response. - */ -void BLERemoteDescriptor::writeValue( - uint8_t newValue, - bool response) { - writeValue(&newValue, 1, response); -} // writeValue - - -#endif /* CONFIG_BT_ENABLED */ diff --git a/lib/ESP32_BLE_Arduino/src/BLERemoteDescriptor.h b/lib/ESP32_BLE_Arduino/src/BLERemoteDescriptor.h deleted file mode 100644 index 7bbc48f1..00000000 --- a/lib/ESP32_BLE_Arduino/src/BLERemoteDescriptor.h +++ /dev/null @@ -1,55 +0,0 @@ -/* - * BLERemoteDescriptor.h - * - * Created on: Jul 8, 2017 - * Author: kolban - */ - -#ifndef COMPONENTS_CPP_UTILS_BLEREMOTEDESCRIPTOR_H_ -#define COMPONENTS_CPP_UTILS_BLEREMOTEDESCRIPTOR_H_ -#include "sdkconfig.h" -#if defined(CONFIG_BT_ENABLED) -#include - -#include - -#include "BLERemoteCharacteristic.h" -#include "BLEUUID.h" -#include "FreeRTOS.h" - -class BLERemoteCharacteristic; -/** - * @brief A model of remote %BLE descriptor. - */ -class BLERemoteDescriptor { -public: - uint16_t getHandle(); - BLERemoteCharacteristic* getRemoteCharacteristic(); - BLEUUID getUUID(); - std::string readValue(void); - uint8_t readUInt8(void); - uint16_t readUInt16(void); - uint32_t readUInt32(void); - std::string toString(void); - void writeValue(uint8_t* data, size_t length, bool response = false); - void writeValue(std::string newValue, bool response = false); - void writeValue(uint8_t newValue, bool response = false); - - -private: - friend class BLERemoteCharacteristic; - BLERemoteDescriptor( - uint16_t handle, - BLEUUID uuid, - BLERemoteCharacteristic* pRemoteCharacteristic - ); - uint16_t m_handle; // Server handle of this descriptor. - BLEUUID m_uuid; // UUID of this descriptor. - std::string m_value; // Last received value of the descriptor. - BLERemoteCharacteristic* m_pRemoteCharacteristic; // Reference to the Remote characteristic of which this descriptor is associated. - FreeRTOS::Semaphore m_semaphoreReadDescrEvt = FreeRTOS::Semaphore("ReadDescrEvt"); - - -}; -#endif /* CONFIG_BT_ENABLED */ -#endif /* COMPONENTS_CPP_UTILS_BLEREMOTEDESCRIPTOR_H_ */ diff --git a/lib/ESP32_BLE_Arduino/src/BLERemoteService.cpp b/lib/ESP32_BLE_Arduino/src/BLERemoteService.cpp deleted file mode 100644 index 78ff9914..00000000 --- a/lib/ESP32_BLE_Arduino/src/BLERemoteService.cpp +++ /dev/null @@ -1,328 +0,0 @@ -/* - * BLERemoteService.cpp - * - * Created on: Jul 8, 2017 - * Author: kolban - */ -#include "sdkconfig.h" -#if defined(CONFIG_BT_ENABLED) - -#include -#include "BLERemoteService.h" -#include "BLEUtils.h" -#include "GeneralUtils.h" -#include -#include -#ifdef ARDUINO_ARCH_ESP32 -#include "esp32-hal-log.h" -#endif - -static const char* LOG_TAG = "BLERemoteService"; - -BLERemoteService::BLERemoteService( - esp_gatt_id_t srvcId, - BLEClient* pClient, - uint16_t startHandle, - uint16_t endHandle - ) { - - ESP_LOGD(LOG_TAG, ">> BLERemoteService()"); - m_srvcId = srvcId; - m_pClient = pClient; - m_uuid = BLEUUID(m_srvcId); - m_haveCharacteristics = false; - m_startHandle = startHandle; - m_endHandle = endHandle; - - ESP_LOGD(LOG_TAG, "<< BLERemoteService()"); -} - - -BLERemoteService::~BLERemoteService() { - removeCharacteristics(); -} - -/* -static bool compareSrvcId(esp_gatt_srvc_id_t id1, esp_gatt_srvc_id_t id2) { - if (id1.id.inst_id != id2.id.inst_id) { - return false; - } - if (!BLEUUID(id1.id.uuid).equals(BLEUUID(id2.id.uuid))) { - return false; - } - return true; -} // compareSrvcId -*/ - -/** - * @brief Handle GATT Client events - */ -void BLERemoteService::gattClientEventHandler( - esp_gattc_cb_event_t event, - esp_gatt_if_t gattc_if, - esp_ble_gattc_cb_param_t *evtParam) { - switch(event) { - // - // ESP_GATTC_GET_CHAR_EVT - // - // get_char: - // - esp_gatt_status_t status - // - uin1t6_t conn_id - // - esp_gatt_srvc_id_t srvc_id - // - esp_gatt_id_t char_id - // - esp_gatt_char_prop_t char_prop - // - /* - case ESP_GATTC_GET_CHAR_EVT: { - // Is this event for this service? If yes, then the local srvc_id and the event srvc_id will be - // the same. - if (compareSrvcId(m_srvcId, evtParam->get_char.srvc_id) == false) { - break; - } - - // If the status is NOT OK then we have a problem and continue. - if (evtParam->get_char.status != ESP_GATT_OK) { - m_semaphoreGetCharEvt.give(); - break; - } - - // This is an indication that we now have the characteristic details for a characteristic owned - // by this service so remember it. - m_characteristicMap.insert(std::pair( - BLEUUID(evtParam->get_char.char_id.uuid).toString(), - new BLERemoteCharacteristic(evtParam->get_char.char_id, evtParam->get_char.char_prop, this) )); - - - // Now that we have received a characteristic, lets ask for the next one. - esp_err_t errRc = ::esp_ble_gattc_get_characteristic( - m_pClient->getGattcIf(), - m_pClient->getConnId(), - &m_srvcId, - &evtParam->get_char.char_id); - if (errRc != ESP_OK) { - ESP_LOGE(LOG_TAG, "esp_ble_gattc_get_characteristic: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - break; - } - - //m_semaphoreGetCharEvt.give(); - break; - } // ESP_GATTC_GET_CHAR_EVT -*/ - default: { - break; - } - } // switch - - // Send the event to each of the characteristics owned by this service. - for (auto &myPair : m_characteristicMap) { - myPair.second->gattClientEventHandler(event, gattc_if, evtParam); - } -} // gattClientEventHandler - - -/** - * @brief Get the remote characteristic object for the characteristic UUID. - * @param [in] uuid Remote characteristic uuid. - * @return Reference to the remote characteristic object. - * @throws BLEUuidNotFoundException - */ -BLERemoteCharacteristic* BLERemoteService::getCharacteristic(const char* uuid) { - return getCharacteristic(BLEUUID(uuid)); -} // getCharacteristic - - -/** - * @brief Get the characteristic object for the UUID. - * @param [in] uuid Characteristic uuid. - * @return Reference to the characteristic object. - * @throws BLEUuidNotFoundException - */ -BLERemoteCharacteristic* BLERemoteService::getCharacteristic(BLEUUID uuid) { -// Design -// ------ -// We wish to retrieve the characteristic given its UUID. It is possible that we have not yet asked the -// device what characteristics it has in which case we have nothing to match against. If we have not -// asked the device about its characteristics, then we do that now. Once we get the results we can then -// examine the characteristics map to see if it has the characteristic we are looking for. - if (!m_haveCharacteristics) { - retrieveCharacteristics(); - } - std::string v = uuid.toString(); - for (auto &myPair : m_characteristicMap) { - if (myPair.first == v) { - return myPair.second; - } - } - throw new BLEUuidNotFoundException(); -} // getCharacteristic - - -/** - * @brief Retrieve all the characteristics for this service. - * This function will not return until we have all the characteristics. - * @return N/A - */ -void BLERemoteService::retrieveCharacteristics() { - - ESP_LOGD(LOG_TAG, ">> getCharacteristics() for service: %s", getUUID().toString().c_str()); - - removeCharacteristics(); // Forget any previous characteristics. - - uint16_t offset = 0; - esp_gattc_char_elem_t result; - while(1) { - uint16_t count = 1; - esp_gatt_status_t status = ::esp_ble_gattc_get_all_char( - getClient()->getGattcIf(), - getClient()->getConnId(), - m_startHandle, - m_endHandle, - &result, - &count, - offset - ); - - if (status == ESP_GATT_INVALID_OFFSET) { // We have reached the end of the entries. - break; - } - - if (status != ESP_GATT_OK) { // If we got an error, end. - ESP_LOGE(LOG_TAG, "esp_ble_gattc_get_all_char: %s", BLEUtils::gattStatusToString(status).c_str()); - break; - } - - if (count == 0) { // If we failed to get any new records, end. - break; - } - - ESP_LOGD(LOG_TAG, "Found a characteristic: Handle: %d, UUID: %s", result.char_handle, BLEUUID(result.uuid).toString().c_str()); - - // We now have a new characteristic ... let us add that to our set of known characteristics - BLERemoteCharacteristic *pNewRemoteCharacteristic = new BLERemoteCharacteristic( - result.char_handle, - BLEUUID(result.uuid), - result.properties, - this - ); - - m_characteristicMap.insert(std::pair(pNewRemoteCharacteristic->getUUID().toString(), pNewRemoteCharacteristic)); - - offset++; // Increment our count of number of descriptors found. - } // Loop forever (until we break inside the loop). - - m_haveCharacteristics = true; // Remember that we have received the characteristics. - ESP_LOGD(LOG_TAG, "<< getCharacteristics()"); -} // getCharacteristics - - -/** - * @brief Retrieve a map of all the characteristics of this service. - * @return A map of all the characteristics of this service. - */ -std::map * BLERemoteService::getCharacteristics() { - ESP_LOGD(LOG_TAG, ">> getCharacteristics() for service: %s", getUUID().toString().c_str()); - // If is possible that we have not read the characteristics associated with the service so do that - // now. The request to retrieve the characteristics by calling "retrieveCharacteristics" is a blocking - // call and does not return until all the characteristics are available. - if (!m_haveCharacteristics) { - retrieveCharacteristics(); - } - ESP_LOGD(LOG_TAG, "<< getCharacteristics() for service: %s", getUUID().toString().c_str()); - return &m_characteristicMap; -} // getCharacteristics - - -/** - * @brief Get the client associated with this service. - * @return A reference to the client associated with this service. - */ -BLEClient* BLERemoteService::getClient() { - return m_pClient; -} // getClient - - -uint16_t BLERemoteService::getEndHandle() { - return m_endHandle; -} // getEndHandle - - -esp_gatt_id_t* BLERemoteService::getSrvcId() { - return &m_srvcId; -} // getSrvcId - - -uint16_t BLERemoteService::getStartHandle() { - return m_startHandle; -} // getStartHandle - - -uint16_t BLERemoteService::getHandle() { - ESP_LOGD(LOG_TAG, ">> getHandle: service: %s", getUUID().toString().c_str()); - ESP_LOGD(LOG_TAG, "<< getHandle: %d 0x%.2x", getStartHandle(), getStartHandle()); - return getStartHandle(); -} // getHandle - - -BLEUUID BLERemoteService::getUUID() { - return m_uuid; -} - -/** - * @brief Read the value of a characteristic associated with this service. - */ -std::string BLERemoteService::getValue(BLEUUID characteristicUuid) { - ESP_LOGD(LOG_TAG, ">> readValue: uuid: %s", characteristicUuid.toString().c_str()); - std::string ret = getCharacteristic(characteristicUuid)->readValue(); - ESP_LOGD(LOG_TAG, "<< readValue"); - return ret; -} // readValue - - - -/** - * @brief Delete the characteristics in the characteristics map. - * We maintain a map called m_characteristicsMap that contains pointers to BLERemoteCharacteristic - * object references. Since we allocated these in this class, we are also responsible for deleteing - * them. This method does just that. - * @return N/A. - */ -void BLERemoteService::removeCharacteristics() { - for (auto &myPair : m_characteristicMap) { - delete myPair.second; - //m_characteristicMap.erase(myPair.first); // Should be no need to delete as it will be deleted by the clear - } - m_characteristicMap.clear(); // Clear the map -} // removeCharacteristics - - -/** - * @brief Set the value of a characteristic. - * @param [in] characteristicUuid The characteristic to set. - * @param [in] value The value to set. - * @throws BLEUuidNotFound - */ -void BLERemoteService::setValue(BLEUUID characteristicUuid, std::string value) { - ESP_LOGD(LOG_TAG, ">> setValue: uuid: %s", characteristicUuid.toString().c_str()); - getCharacteristic(characteristicUuid)->writeValue(value); - ESP_LOGD(LOG_TAG, "<< setValue"); -} // setValue - - -/** - * @brief Create a string representation of this remote service. - * @return A string representation of this remote service. - */ -std::string BLERemoteService::toString() { - std::ostringstream ss; - ss << "Service: uuid: " + m_uuid.toString(); - ss << ", start_handle: " << std::dec << m_startHandle << " 0x" << std::hex << m_startHandle << - ", end_handle: " << std::dec << m_endHandle << " 0x" << std::hex << m_endHandle; - for (auto &myPair : m_characteristicMap) { - ss << "\n" << myPair.second->toString(); - // myPair.second is the value - } - return ss.str(); -} // toString - - -#endif /* CONFIG_BT_ENABLED */ diff --git a/lib/ESP32_BLE_Arduino/src/BLERemoteService.h b/lib/ESP32_BLE_Arduino/src/BLERemoteService.h deleted file mode 100644 index 222c6e45..00000000 --- a/lib/ESP32_BLE_Arduino/src/BLERemoteService.h +++ /dev/null @@ -1,85 +0,0 @@ -/* - * BLERemoteService.h - * - * Created on: Jul 8, 2017 - * Author: kolban - */ - -#ifndef COMPONENTS_CPP_UTILS_BLEREMOTESERVICE_H_ -#define COMPONENTS_CPP_UTILS_BLEREMOTESERVICE_H_ -#include "sdkconfig.h" -#if defined(CONFIG_BT_ENABLED) - -#include - -#include "BLEClient.h" -#include "BLERemoteCharacteristic.h" -#include "BLEUUID.h" -#include "FreeRTOS.h" - -class BLEClient; -class BLERemoteCharacteristic; - - -/** - * @brief A model of a remote %BLE service. - */ -class BLERemoteService { -public: - - virtual ~BLERemoteService(); - - // Public methods - BLERemoteCharacteristic* getCharacteristic(const char* uuid); // Get the specified characteristic reference. - BLERemoteCharacteristic* getCharacteristic(BLEUUID uuid); // Get the specified characteristic reference. - BLERemoteCharacteristic* getCharacteristic(uint16_t uuid); // Get the specified characteristic reference. - std::map* getCharacteristics(); - void getCharacteristics(std::map* pCharacteristicMap); // Get the characteristics map. - - BLEClient* getClient(void); // Get a reference to the client associated with this service. - uint16_t getHandle(); // Get the handle of this service. - BLEUUID getUUID(void); // Get the UUID of this service. - std::string getValue(BLEUUID characteristicUuid); // Get the value of a characteristic. - void setValue(BLEUUID characteristicUuid, std::string value); // Set the value of a characteristic. - std::string toString(void); - -private: - // Private constructor ... never meant to be created by a user application. - BLERemoteService(esp_gatt_id_t srvcId, BLEClient* pClient, uint16_t startHandle, uint16_t endHandle); - - // Friends - friend class BLEClient; - friend class BLERemoteCharacteristic; - - // Private methods - void retrieveCharacteristics(void); // Retrieve the characteristics from the BLE Server. - esp_gatt_id_t* getSrvcId(void); - uint16_t getStartHandle(); // Get the start handle for this service. - uint16_t getEndHandle(); // Get the end handle for this service. - - void gattClientEventHandler( - esp_gattc_cb_event_t event, - esp_gatt_if_t gattc_if, - esp_ble_gattc_cb_param_t* evtParam); - - void removeCharacteristics(); - - // Properties - - // We maintain a map of characteristics owned by this service keyed by a string representation of the UUID. - std::map m_characteristicMap; - - // We maintain a map of characteristics owned by this service keyed by a handle. - std::map m_characteristicMapByHandle; - - bool m_haveCharacteristics; // Have we previously obtained the characteristics. - BLEClient* m_pClient; - FreeRTOS::Semaphore m_semaphoreGetCharEvt = FreeRTOS::Semaphore("GetCharEvt"); - esp_gatt_id_t m_srvcId; - BLEUUID m_uuid; // The UUID of this service. - uint16_t m_startHandle; // The starting handle of this service. - uint16_t m_endHandle; // The ending handle of this service. -}; // BLERemoteService - -#endif /* CONFIG_BT_ENABLED */ -#endif /* COMPONENTS_CPP_UTILS_BLEREMOTESERVICE_H_ */ diff --git a/lib/ESP32_BLE_Arduino/src/BLEScan.cpp b/lib/ESP32_BLE_Arduino/src/BLEScan.cpp deleted file mode 100644 index 3046b7c8..00000000 --- a/lib/ESP32_BLE_Arduino/src/BLEScan.cpp +++ /dev/null @@ -1,292 +0,0 @@ -/* - * BLEScan.cpp - * - * Created on: Jul 1, 2017 - * Author: kolban - */ -#include "sdkconfig.h" -#if defined(CONFIG_BT_ENABLED) - - -#include -#include - -#include - -#include "BLEAdvertisedDevice.h" -#include "BLEScan.h" -#include "BLEUtils.h" -#include "GeneralUtils.h" -#ifdef ARDUINO_ARCH_ESP32 -#include "esp32-hal-log.h" -#endif - -static const char* LOG_TAG = "BLEScan"; - - -/** - * Constructor - */ -BLEScan::BLEScan() { - m_scan_params.scan_type = BLE_SCAN_TYPE_PASSIVE; // Default is a passive scan. - m_scan_params.own_addr_type = BLE_ADDR_TYPE_PUBLIC; - m_scan_params.scan_filter_policy = BLE_SCAN_FILTER_ALLOW_ALL; - m_pAdvertisedDeviceCallbacks = nullptr; - m_stopped = true; - m_wantDuplicates = false; - setInterval(100); - setWindow(100); -} // BLEScan - - -/** - * @brief Handle GAP events related to scans. - * @param [in] event The event type for this event. - * @param [in] param Parameter data for this event. - */ -void BLEScan::handleGAPEvent( - esp_gap_ble_cb_event_t event, - esp_ble_gap_cb_param_t* param) { - - switch(event) { - - // ESP_GAP_BLE_SCAN_RESULT_EVT - // --------------------------- - // scan_rst: - // esp_gap_search_evt_t search_evt - // esp_bd_addr_t bda - // esp_bt_dev_type_t dev_type - // esp_ble_addr_type_t ble_addr_type - // esp_ble_evt_type_t ble_evt_type - // int rssi - // uint8_t ble_adv[ESP_BLE_ADV_DATA_LEN_MAX] - // int flag - // int num_resps - // uint8_t adv_data_len - // uint8_t scan_rsp_len - case ESP_GAP_BLE_SCAN_RESULT_EVT: { - - switch(param->scan_rst.search_evt) { - // - // ESP_GAP_SEARCH_INQ_CMPL_EVT - // - // Event that indicates that the duration allowed for the search has completed or that we have been - // asked to stop. - case ESP_GAP_SEARCH_INQ_CMPL_EVT: { - m_stopped = true; - if (m_scanCompleteCB != nullptr) { - m_scanCompleteCB(m_scanResults); - } - m_semaphoreScanEnd.give(); - break; - } // ESP_GAP_SEARCH_INQ_CMPL_EVT - - // - // ESP_GAP_SEARCH_INQ_RES_EVT - // - // Result that has arrived back from a Scan inquiry. - case ESP_GAP_SEARCH_INQ_RES_EVT: { - if (m_stopped) { // If we are not scanning, nothing to do with the extra results. - break; - } - -// Examine our list of previously scanned addresses and, if we found this one already, -// ignore it. - BLEAddress advertisedAddress(param->scan_rst.bda); - bool found = false; - - for (int i=0; iscan_rst.rssi); - advertisedDevice.setAdFlag(param->scan_rst.flag); - advertisedDevice.parseAdvertisement((uint8_t*)param->scan_rst.ble_adv); - advertisedDevice.setScan(this); - - if (m_pAdvertisedDeviceCallbacks) { - m_pAdvertisedDeviceCallbacks->onResult(advertisedDevice); - } - - if (!found) { // If we have previously seen this device, don't record it again. - m_scanResults.m_vectorAdvertisedDevices.push_back(advertisedDevice); - } - - break; - } // ESP_GAP_SEARCH_INQ_RES_EVT - - default: { - break; - } - } // switch - search_evt - - - break; - } // ESP_GAP_BLE_SCAN_RESULT_EVT - - default: { - break; - } // default - } // End switch -} // gapEventHandler - - -/** - * @brief Should we perform an active or passive scan? - * The default is a passive scan. An active scan means that we will wish a scan response. - * @param [in] active If true, we perform an active scan otherwise a passive scan. - * @return N/A. - */ -void BLEScan::setActiveScan(bool active) { - if (active) { - m_scan_params.scan_type = BLE_SCAN_TYPE_ACTIVE; - } else { - m_scan_params.scan_type = BLE_SCAN_TYPE_PASSIVE; - } -} // setActiveScan - - -/** - * @brief Set the call backs to be invoked. - * @param [in] pAdvertisedDeviceCallbacks Call backs to be invoked. - * @param [in] wantDuplicates True if we wish to be called back with duplicates. Default is false. - */ -void BLEScan::setAdvertisedDeviceCallbacks(BLEAdvertisedDeviceCallbacks* pAdvertisedDeviceCallbacks, bool wantDuplicates) { - m_wantDuplicates = wantDuplicates; - m_pAdvertisedDeviceCallbacks = pAdvertisedDeviceCallbacks; -} // setAdvertisedDeviceCallbacks - - -/** - * @brief Set the interval to scan. - * @param [in] The interval in msecs. - */ -void BLEScan::setInterval(uint16_t intervalMSecs) { - m_scan_params.scan_interval = intervalMSecs / 0.625; -} // setInterval - - -/** - * @brief Set the window to actively scan. - * @param [in] windowMSecs How long to actively scan. - */ -void BLEScan::setWindow(uint16_t windowMSecs) { - m_scan_params.scan_window = windowMSecs / 0.625; -} // setWindow - - -/** - * @brief Start scanning. - * @param [in] duration The duration in seconds for which to scan. - * @param [in] scanCompleteCB A function to be called when scanning has completed. - * @return True if scan started or false if there was an error. - */ -bool BLEScan::start(uint32_t duration, void (*scanCompleteCB)(BLEScanResults)) { - ESP_LOGD(LOG_TAG, ">> start(duration=%d)", duration); - - m_semaphoreScanEnd.take(std::string("start")); - m_scanCompleteCB = scanCompleteCB; // Save the callback to be invoked when the scan completes. - - m_scanResults.m_vectorAdvertisedDevices.clear(); - - esp_err_t errRc = ::esp_ble_gap_set_scan_params(&m_scan_params); - - if (errRc != ESP_OK) { - ESP_LOGE(LOG_TAG, "esp_ble_gap_set_scan_params: err: %d, text: %s", errRc, GeneralUtils::errorToString(errRc)); - m_semaphoreScanEnd.give(); - return false; - } - - errRc = ::esp_ble_gap_start_scanning(duration); - - if (errRc != ESP_OK) { - ESP_LOGE(LOG_TAG, "esp_ble_gap_start_scanning: err: %d, text: %s", errRc, GeneralUtils::errorToString(errRc)); - m_semaphoreScanEnd.give(); - return false; - } - - m_stopped = false; - - ESP_LOGD(LOG_TAG, "<< start()"); - return true; -} // start - - -/** - * @brief Start scanning and block until scanning has been completed. - * @param [in] duration The duration in seconds for which to scan. - * @return The BLEScanResults. - */ -BLEScanResults BLEScan::start(uint32_t duration) { - if(start(duration, nullptr)) { - m_semaphoreScanEnd.wait("start"); // Wait for the semaphore to release. - } - return m_scanResults; -} // start - - -/** - * @brief Stop an in progress scan. - * @return N/A. - */ -void BLEScan::stop() { - ESP_LOGD(LOG_TAG, ">> stop()"); - - esp_err_t errRc = ::esp_ble_gap_stop_scanning(); - - m_stopped = true; - - if (errRc != ESP_OK) { - ESP_LOGE(LOG_TAG, "esp_ble_gap_stop_scanning: err: %d, text: %s", errRc, GeneralUtils::errorToString(errRc)); - return; - } - - m_semaphoreScanEnd.give(); - - ESP_LOGD(LOG_TAG, "<< stop()"); -} // stop - - -/** - * @brief Dump the scan results to the log. - */ -void BLEScanResults::dump() { - ESP_LOGD(LOG_TAG, ">> Dump scan results:"); - for (int i=0; i - -#include -#include "BLEAdvertisedDevice.h" -#include "BLEClient.h" -#include "FreeRTOS.h" - -class BLEAdvertisedDevice; -class BLEAdvertisedDeviceCallbacks; -class BLEClient; -class BLEScan; - - -/** - * @brief The result of having performed a scan. - * When a scan completes, we have a set of found devices. Each device is described - * by a BLEAdvertisedDevice object. The number of items in the set is given by - * getCount(). We can retrieve a device by calling getDevice() passing in the - * index (starting at 0) of the desired device. - */ -class BLEScanResults { -public: - void dump(); - int getCount(); - BLEAdvertisedDevice getDevice(uint32_t i); - -private: - friend BLEScan; - std::vector m_vectorAdvertisedDevices; -}; - -/** - * @brief Perform and manage %BLE scans. - * - * Scanning is associated with a %BLE client that is attempting to locate BLE servers. - */ -class BLEScan { -public: - void setActiveScan(bool active); - void setAdvertisedDeviceCallbacks( - BLEAdvertisedDeviceCallbacks* pAdvertisedDeviceCallbacks, - bool wantDuplicates = false); - void setInterval(uint16_t intervalMSecs); - void setWindow(uint16_t windowMSecs); - bool start(uint32_t duration, void (*scanCompleteCB)(BLEScanResults)); - BLEScanResults start(uint32_t duration); - void stop(); - -private: - BLEScan(); // One doesn't create a new instance instead one asks the BLEDevice for the singleton. - friend class BLEDevice; - void handleGAPEvent( - esp_gap_ble_cb_event_t event, - esp_ble_gap_cb_param_t* param); - void parseAdvertisement(BLEClient* pRemoteDevice, uint8_t *payload); - - - esp_ble_scan_params_t m_scan_params; - BLEAdvertisedDeviceCallbacks* m_pAdvertisedDeviceCallbacks; - bool m_stopped; - FreeRTOS::Semaphore m_semaphoreScanEnd = FreeRTOS::Semaphore("ScanEnd"); - BLEScanResults m_scanResults; - bool m_wantDuplicates; - void (*m_scanCompleteCB)(BLEScanResults scanResults); -}; // BLEScan - -#endif /* CONFIG_BT_ENABLED */ -#endif /* COMPONENTS_CPP_UTILS_BLESCAN_H_ */ diff --git a/lib/ESP32_BLE_Arduino/src/BLESecurity.cpp b/lib/ESP32_BLE_Arduino/src/BLESecurity.cpp deleted file mode 100644 index 4cf964a7..00000000 --- a/lib/ESP32_BLE_Arduino/src/BLESecurity.cpp +++ /dev/null @@ -1,105 +0,0 @@ -/* - * BLESecurity.cpp - * - * Created on: Dec 17, 2017 - * Author: chegewara - */ - -#include -#include "sdkconfig.h" -#if defined(CONFIG_BT_ENABLED) - -BLESecurity::BLESecurity() { -} - -BLESecurity::~BLESecurity() { -} -/* - * @brief Set requested authentication mode - */ -void BLESecurity::setAuthenticationMode(esp_ble_auth_req_t auth_req) { - m_authReq = auth_req; - esp_ble_gap_set_security_param(ESP_BLE_SM_AUTHEN_REQ_MODE, &m_authReq, sizeof(uint8_t)); // <--- setup requested authentication mode -} - -/** - * @brief Set our device IO capability to let end user perform authorization - * either by displaying or entering generated 6-digits pin code - */ -void BLESecurity::setCapability(esp_ble_io_cap_t iocap) { - m_iocap = iocap; - esp_ble_gap_set_security_param(ESP_BLE_SM_IOCAP_MODE, &iocap, sizeof(uint8_t)); -} // setCapability - - -/** - * @brief Init encryption key by server - * @param key_size is value between 7 and 16 - */ -void BLESecurity::setInitEncryptionKey(uint8_t init_key) { - m_initKey = init_key; - esp_ble_gap_set_security_param(ESP_BLE_SM_SET_INIT_KEY, &m_initKey, sizeof(uint8_t)); -} // setInitEncryptionKey - - -/** - * @brief Init encryption key by client - * @param key_size is value between 7 and 16 - */ -void BLESecurity::setRespEncryptionKey(uint8_t resp_key) { - m_respKey = resp_key; - esp_ble_gap_set_security_param(ESP_BLE_SM_SET_RSP_KEY, &m_respKey, sizeof(uint8_t)); -} // setRespEncryptionKey - - -/** - * - * - */ -void BLESecurity::setKeySize(uint8_t key_size) { - m_keySize = key_size; - esp_ble_gap_set_security_param(ESP_BLE_SM_MAX_KEY_SIZE, &m_keySize, sizeof(uint8_t)); -} //setKeySize - - -/** - * @brief Debug function to display what keys are exchanged by peers - */ -char* BLESecurity::esp_key_type_to_str(esp_ble_key_type_t key_type) -{ - char* key_str = nullptr; - switch(key_type) { - case ESP_LE_KEY_NONE: - key_str = (char*)"ESP_LE_KEY_NONE"; - break; - case ESP_LE_KEY_PENC: - key_str = (char*)"ESP_LE_KEY_PENC"; - break; - case ESP_LE_KEY_PID: - key_str = (char*)"ESP_LE_KEY_PID"; - break; - case ESP_LE_KEY_PCSRK: - key_str = (char*)"ESP_LE_KEY_PCSRK"; - break; - case ESP_LE_KEY_PLK: - key_str = (char*)"ESP_LE_KEY_PLK"; - break; - case ESP_LE_KEY_LLK: - key_str = (char*)"ESP_LE_KEY_LLK"; - break; - case ESP_LE_KEY_LENC: - key_str = (char*)"ESP_LE_KEY_LENC"; - break; - case ESP_LE_KEY_LID: - key_str = (char*)"ESP_LE_KEY_LID"; - break; - case ESP_LE_KEY_LCSRK: - key_str = (char*)"ESP_LE_KEY_LCSRK"; - break; - default: - key_str = (char*)"INVALID BLE KEY TYPE"; - break; - } - return key_str; -} // esp_key_type_to_str -#endif // CONFIG_BT_ENABLED diff --git a/lib/ESP32_BLE_Arduino/src/BLESecurity.h b/lib/ESP32_BLE_Arduino/src/BLESecurity.h deleted file mode 100644 index 67c41efb..00000000 --- a/lib/ESP32_BLE_Arduino/src/BLESecurity.h +++ /dev/null @@ -1,71 +0,0 @@ -/* - * BLESecurity.h - * - * Created on: Dec 17, 2017 - * Author: chegewara - */ - -#ifndef COMPONENTS_CPP_UTILS_BLESECURITY_H_ -#define COMPONENTS_CPP_UTILS_BLESECURITY_H_ -#include "sdkconfig.h" -#if defined(CONFIG_BT_ENABLED) - -#include - -class BLESecurity { -public: - BLESecurity(); - virtual ~BLESecurity(); - void setAuthenticationMode(esp_ble_auth_req_t auth_req); - void setCapability(esp_ble_io_cap_t iocap); - void setInitEncryptionKey(uint8_t init_key); - void setRespEncryptionKey(uint8_t resp_key); - void setKeySize(uint8_t key_size = 16); - static char* esp_key_type_to_str(esp_ble_key_type_t key_type); - -private: - esp_ble_auth_req_t m_authReq; - esp_ble_io_cap_t m_iocap; - uint8_t m_initKey; - uint8_t m_respKey; - uint8_t m_keySize; -}; // BLESecurity - - -/* - * @brief Callbacks to handle GAP events related to authorization - */ -class BLESecurityCallbacks { -public: - virtual ~BLESecurityCallbacks() {}; - - /** - * @brief Its request from peer device to input authentication pin code displayed on peer device. - * It requires that our device is capable to input 6-digits code by end user - * @return Return 6-digits integer value from input device - */ - virtual uint32_t onPassKeyRequest() = 0; - - /** - * @brief Provide us 6-digits code to perform authentication. - * It requires that our device is capable to display this code to end user - * @param - */ - virtual void onPassKeyNotify(uint32_t pass_key); - - /** - * @brief Here we can make decision if we want to let negotiate authorization with peer device or not - * return Return true if we accept this peer device request - */ - - virtual bool onSecurityRequest(); - /** - * Provide us information when authentication process is completed - */ - virtual void onAuthenticationComplete(esp_ble_auth_cmpl_t); - - virtual bool onConfirmPIN(uint32_t pin); -}; // BLESecurityCallbacks - -#endif // CONFIG_BT_ENABLED -#endif // COMPONENTS_CPP_UTILS_BLESECURITY_H_ diff --git a/lib/ESP32_BLE_Arduino/src/BLEServer.cpp b/lib/ESP32_BLE_Arduino/src/BLEServer.cpp deleted file mode 100644 index d5c9de68..00000000 --- a/lib/ESP32_BLE_Arduino/src/BLEServer.cpp +++ /dev/null @@ -1,361 +0,0 @@ -/* - * BLEServer.cpp - * - * Created on: Apr 16, 2017 - * Author: kolban - */ - -#include "sdkconfig.h" -#if defined(CONFIG_BT_ENABLED) -#include -#include -#include -#include -//#include -#include "BLEDevice.h" -#include "BLEServer.h" -#include "BLEService.h" -#include "BLEUtils.h" -#include -#include -#include -#ifdef ARDUINO_ARCH_ESP32 -#include "esp32-hal-log.h" -#endif - -static const char* LOG_TAG = "BLEServer"; - - -/** - * @brief Construct a %BLE Server - * - * This class is not designed to be individually instantiated. Instead one should create a server by asking - * the BLEDevice class. - */ -BLEServer::BLEServer() { - m_appId = -1; - m_gatts_if = -1; - m_connectedCount = 0; - m_connId = -1; - m_pServerCallbacks = nullptr; - - //createApp(0); -} // BLEServer - - -void BLEServer::createApp(uint16_t appId) { - m_appId = appId; - registerApp(); -} // createApp - - -/** - * @brief Create a %BLE Service. - * - * With a %BLE server, we can host one or more services. Invoking this function causes the creation of a definition - * of a new service. Every service must have a unique UUID. - * @param [in] uuid The UUID of the new service. - * @return A reference to the new service object. - */ -BLEService* BLEServer::createService(const char* uuid) { - return createService(BLEUUID(uuid)); -} - - -/** - * @brief Create a %BLE Service. - * - * With a %BLE server, we can host one or more services. Invoking this function causes the creation of a definition - * of a new service. Every service must have a unique UUID. - * @param [in] uuid The UUID of the new service. - * @param [in] numHandles The maximum number of handles associated with this service. - * @param [in] inst_id With multiple services with the same UUID we need to provide inst_id value different for each service. - * @return A reference to the new service object. - */ -BLEService* BLEServer::createService(BLEUUID uuid, uint32_t numHandles, uint8_t inst_id) { - ESP_LOGD(LOG_TAG, ">> createService - %s", uuid.toString().c_str()); - m_semaphoreCreateEvt.take("createService"); - - // Check that a service with the supplied UUID does not already exist. - if (m_serviceMap.getByUUID(uuid) != nullptr) { - ESP_LOGW(LOG_TAG, "<< Attempt to create a new service with uuid %s but a service with that UUID already exists.", - uuid.toString().c_str()); - //m_semaphoreCreateEvt.give(); - //return nullptr; - } - - BLEService* pService = new BLEService(uuid, numHandles); - pService->m_id = inst_id; - m_serviceMap.setByUUID(uuid, pService); // Save a reference to this service being on this server. - pService->executeCreate(this); // Perform the API calls to actually create the service. - - m_semaphoreCreateEvt.wait("createService"); - - ESP_LOGD(LOG_TAG, "<< createService"); - return pService; -} // createService - - -/** - * @brief Retrieve the advertising object that can be used to advertise the existence of the server. - * - * @return An advertising object. - */ -BLEAdvertising* BLEServer::getAdvertising() { - return &m_bleAdvertising; -} - -uint16_t BLEServer::getConnId() { - return m_connId; -} - - -/** - * @brief Return the number of connected clients. - * @return The number of connected clients. - */ -uint32_t BLEServer::getConnectedCount() { - return m_connectedCount; -} // getConnectedCount - - -uint16_t BLEServer::getGattsIf() { - return m_gatts_if; -} - -/** - * @brief Handle a received GAP event. - * - * @param [in] event - * @param [in] param - */ -void BLEServer::handleGAPEvent( - esp_gap_ble_cb_event_t event, - esp_ble_gap_cb_param_t* param) { - ESP_LOGD(LOG_TAG, "BLEServer ... handling GAP event!"); - switch(event) { - case ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT: { - /* - esp_ble_adv_params_t adv_params; - adv_params.adv_int_min = 0x20; - adv_params.adv_int_max = 0x40; - adv_params.adv_type = ADV_TYPE_IND; - adv_params.own_addr_type = BLE_ADDR_TYPE_PUBLIC; - adv_params.channel_map = ADV_CHNL_ALL; - adv_params.adv_filter_policy = ADV_FILTER_ALLOW_SCAN_ANY_CON_ANY; - ESP_LOGD(tag, "Starting advertising"); - esp_err_t errRc = ::esp_ble_gap_start_advertising(&adv_params); - if (errRc != ESP_OK) { - ESP_LOGE(tag, "esp_ble_gap_start_advertising: rc=%d %s", errRc, espToString(errRc)); - return; - } - */ - break; - } - - default: - break; - } -} // handleGAPEvent - - - -/** - * @brief Handle a GATT Server Event. - * - * @param [in] event - * @param [in] gatts_if - * @param [in] param - * - */ -void BLEServer::handleGATTServerEvent( - esp_gatts_cb_event_t event, - esp_gatt_if_t gatts_if, - esp_ble_gatts_cb_param_t* param) { - - ESP_LOGD(LOG_TAG, ">> handleGATTServerEvent: %s", - BLEUtils::gattServerEventTypeToString(event).c_str()); - - // Invoke the handler for every Service we have. - m_serviceMap.handleGATTServerEvent(event, gatts_if, param); - - switch(event) { - // ESP_GATTS_ADD_CHAR_EVT - Indicate that a characteristic was added to the service. - // add_char: - // - esp_gatt_status_t status - // - uint16_t attr_handle - // - uint16_t service_handle - // - esp_bt_uuid_t char_uuid - // - case ESP_GATTS_ADD_CHAR_EVT: { - break; - } // ESP_GATTS_ADD_CHAR_EVT - - - // ESP_GATTS_CONNECT_EVT - // connect: - // - uint16_t conn_id - // - esp_bd_addr_t remote_bda - // - bool is_connected - // - case ESP_GATTS_CONNECT_EVT: { - m_connId = param->connect.conn_id; // Save the connection id. - if (m_pServerCallbacks != nullptr) { - m_pServerCallbacks->onConnect(this); - } - m_connectedCount++; // Increment the number of connected devices count. - break; - } // ESP_GATTS_CONNECT_EVT - - - // ESP_GATTS_CREATE_EVT - // Called when a new service is registered as having been created. - // - // create: - // * esp_gatt_status_t status - // * uint16_t service_handle - // * esp_gatt_srvc_id_t service_id - // - case ESP_GATTS_CREATE_EVT: { - BLEService* pService = m_serviceMap.getByUUID(param->create.service_id.id.uuid); - m_serviceMap.setByHandle(param->create.service_handle, pService); - m_semaphoreCreateEvt.give(); - break; - } // ESP_GATTS_CREATE_EVT - - - // ESP_GATTS_DISCONNECT_EVT - // - // disconnect - // - uint16_t conn_id - // - esp_bd_addr_t remote_bda - // - bool is_connected - // - // If we receive a disconnect event then invoke the callback for disconnects (if one is present). - // we also want to start advertising again. - case ESP_GATTS_DISCONNECT_EVT: { - m_connectedCount--; // Decrement the number of connected devices count. - if (m_pServerCallbacks != nullptr) { // If we have callbacks, call now. - m_pServerCallbacks->onDisconnect(this); - } - startAdvertising(); //- do this with some delay from the loop() - break; - } // ESP_GATTS_DISCONNECT_EVT - - - // ESP_GATTS_READ_EVT - A request to read the value of a characteristic has arrived. - // - // read: - // - uint16_t conn_id - // - uint32_t trans_id - // - esp_bd_addr_t bda - // - uint16_t handle - // - uint16_t offset - // - bool is_long - // - bool need_rsp - // - case ESP_GATTS_READ_EVT: { - break; - } // ESP_GATTS_READ_EVT - - - // ESP_GATTS_REG_EVT - // reg: - // - esp_gatt_status_t status - // - uint16_t app_id - // - case ESP_GATTS_REG_EVT: { - m_gatts_if = gatts_if; - m_semaphoreRegisterAppEvt.give(); // Unlock the mutex waiting for the registration of the app. - break; - } // ESP_GATTS_REG_EVT - - - // ESP_GATTS_WRITE_EVT - A request to write the value of a characteristic has arrived. - // - // write: - // - uint16_t conn_id - // - uint16_t trans_id - // - esp_bd_addr_t bda - // - uint16_t handle - // - uint16_t offset - // - bool need_rsp - // - bool is_prep - // - uint16_t len - // - uint8_t* value - // - case ESP_GATTS_WRITE_EVT: { - break; - } - - default: { - break; - } - } - ESP_LOGD(LOG_TAG, "<< handleGATTServerEvent"); -} // handleGATTServerEvent - - -/** - * @brief Register the app. - * - * @return N/A - */ -void BLEServer::registerApp() { - ESP_LOGD(LOG_TAG, ">> registerApp - %d", m_appId); - m_semaphoreRegisterAppEvt.take("registerApp"); // Take the mutex, will be released by ESP_GATTS_REG_EVT event. - ::esp_ble_gatts_app_register(m_appId); - m_semaphoreRegisterAppEvt.wait("registerApp"); - ESP_LOGD(LOG_TAG, "<< registerApp"); -} // registerApp - - -/** - * @brief Set the server callbacks. - * - * As a %BLE server operates, it will generate server level events such as a new client connecting or a previous client - * disconnecting. This function can be called to register a callback handler that will be invoked when these - * events are detected. - * - * @param [in] pCallbacks The callbacks to be invoked. - */ -void BLEServer::setCallbacks(BLEServerCallbacks* pCallbacks) { - m_pServerCallbacks = pCallbacks; -} // setCallbacks - -/* - * Remove service - */ -void BLEServer::removeService(BLEService *service) { - service->stop(); - service->executeDelete(); - m_serviceMap.removeService(service); -} - -/** - * @brief Start advertising. - * - * Start the server advertising its existence. This is a convenience function and is equivalent to - * retrieving the advertising object and invoking start upon it. - */ -void BLEServer::startAdvertising() { - ESP_LOGD(LOG_TAG, ">> startAdvertising"); - m_bleAdvertising.start(); - ESP_LOGD(LOG_TAG, "<< startAdvertising"); -} // startAdvertising - - -void BLEServerCallbacks::onConnect(BLEServer* pServer) { - ESP_LOGD("BLEServerCallbacks", ">> onConnect(): Default"); - ESP_LOGD("BLEServerCallbacks", "Device: %s", BLEDevice::toString().c_str()); - ESP_LOGD("BLEServerCallbacks", "<< onConnect()"); -} // onConnect - - -void BLEServerCallbacks::onDisconnect(BLEServer* pServer) { - ESP_LOGD("BLEServerCallbacks", ">> onDisconnect(): Default"); - ESP_LOGD("BLEServerCallbacks", "Device: %s", BLEDevice::toString().c_str()); - ESP_LOGD("BLEServerCallbacks", "<< onDisconnect()"); -} // onDisconnect - -#endif // CONFIG_BT_ENABLED diff --git a/lib/ESP32_BLE_Arduino/src/BLEServer.h b/lib/ESP32_BLE_Arduino/src/BLEServer.h deleted file mode 100644 index 95c55d53..00000000 --- a/lib/ESP32_BLE_Arduino/src/BLEServer.h +++ /dev/null @@ -1,121 +0,0 @@ -/* - * BLEServer.h - * - * Created on: Apr 16, 2017 - * Author: kolban - */ - -#ifndef COMPONENTS_CPP_UTILS_BLESERVER_H_ -#define COMPONENTS_CPP_UTILS_BLESERVER_H_ -#include "sdkconfig.h" -#if defined(CONFIG_BT_ENABLED) -#include - -#include -#include - -#include "BLEUUID.h" -#include "BLEAdvertising.h" -#include "BLECharacteristic.h" -#include "BLEService.h" -#include "BLESecurity.h" -#include "FreeRTOS.h" - -class BLEServerCallbacks; - - -/** - * @brief A data structure that manages the %BLE servers owned by a BLE server. - */ -class BLEServiceMap { -public: - BLEService* getByHandle(uint16_t handle); - BLEService* getByUUID(const char* uuid); - BLEService* getByUUID(BLEUUID uuid); - void handleGATTServerEvent( - esp_gatts_cb_event_t event, - esp_gatt_if_t gatts_if, - esp_ble_gatts_cb_param_t* param); - void setByHandle(uint16_t handle, BLEService* service); - void setByUUID(const char* uuid, BLEService* service); - void setByUUID(BLEUUID uuid, BLEService* service); - std::string toString(); - BLEService* getFirst(); - BLEService* getNext(); - void removeService(BLEService *service); - -private: - std::map m_handleMap; - std::map m_uuidMap; - std::map::iterator m_iterator; -}; - - -/** - * @brief The model of a %BLE server. - */ -class BLEServer { -public: - uint32_t getConnectedCount(); - BLEService* createService(const char* uuid); - BLEService* createService(BLEUUID uuid, uint32_t numHandles=15, uint8_t inst_id=0); - BLEAdvertising* getAdvertising(); - void setCallbacks(BLEServerCallbacks* pCallbacks); - void startAdvertising(); - void removeService(BLEService *service); - - -private: - BLEServer(); - friend class BLEService; - friend class BLECharacteristic; - friend class BLEDevice; - esp_ble_adv_data_t m_adv_data; - uint16_t m_appId; - BLEAdvertising m_bleAdvertising; - uint16_t m_connId; - uint32_t m_connectedCount; - uint16_t m_gatts_if; - FreeRTOS::Semaphore m_semaphoreRegisterAppEvt = FreeRTOS::Semaphore("RegisterAppEvt"); - FreeRTOS::Semaphore m_semaphoreCreateEvt = FreeRTOS::Semaphore("CreateEvt"); - BLEServiceMap m_serviceMap; - BLEServerCallbacks* m_pServerCallbacks; - - void createApp(uint16_t appId); - uint16_t getConnId(); - uint16_t getGattsIf(); - void handleGAPEvent(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param); - void handleGATTServerEvent(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param); - void registerApp(); -}; // BLEServer - - -/** - * @brief Callbacks associated with the operation of a %BLE server. - */ -class BLEServerCallbacks { -public: - virtual ~BLEServerCallbacks() {}; - /** - * @brief Handle a new client connection. - * - * When a new client connects, we are invoked. - * - * @param [in] pServer A reference to the %BLE server that received the client connection. - */ - virtual void onConnect(BLEServer* pServer); - - /** - * @brief Handle an existing client disconnection. - * - * When an existing client disconnects, we are invoked. - * - * @param [in] pServer A reference to the %BLE server that received the existing client disconnection. - */ - virtual void onDisconnect(BLEServer* pServer); -}; // BLEServerCallbacks - - - -#endif /* CONFIG_BT_ENABLED */ -#endif /* COMPONENTS_CPP_UTILS_BLESERVER_H_ */ diff --git a/lib/ESP32_BLE_Arduino/src/BLEService.cpp b/lib/ESP32_BLE_Arduino/src/BLEService.cpp deleted file mode 100644 index 340ea560..00000000 --- a/lib/ESP32_BLE_Arduino/src/BLEService.cpp +++ /dev/null @@ -1,435 +0,0 @@ -/* - * BLEService.cpp - * - * Created on: Mar 25, 2017 - * Author: kolban - */ - -// A service is identified by a UUID. A service is also the container for one or more characteristics. - -#include "sdkconfig.h" -#if defined(CONFIG_BT_ENABLED) -#include -#include -#include - -#include -#include -#include - -#include "BLEServer.h" -#include "BLEService.h" -#include "BLEUtils.h" -#include "GeneralUtils.h" - -#ifdef ARDUINO_ARCH_ESP32 -#include "esp32-hal-log.h" -#endif - -#define NULL_HANDLE (0xffff) - -static const char* LOG_TAG = "BLEService"; // Tag for logging. - -/** - * @brief Construct an instance of the BLEService - * @param [in] uuid The UUID of the service. - * @param [in] numHandles The maximum number of handles associated with the service. - */ -BLEService::BLEService(const char* uuid, uint32_t numHandles) : BLEService(BLEUUID(uuid), numHandles) { -} - - -/** - * @brief Construct an instance of the BLEService - * @param [in] uuid The UUID of the service. - * @param [in] numHandles The maximum number of handles associated with the service. - */ -BLEService::BLEService(BLEUUID uuid, uint32_t numHandles) { - m_uuid = uuid; - m_handle = NULL_HANDLE; - m_pServer = nullptr; - //m_serializeMutex.setName("BLEService"); - m_lastCreatedCharacteristic = nullptr; - m_numHandles = numHandles; -} // BLEService - - -/** - * @brief Create the service. - * Create the service. - * @param [in] gatts_if The handle of the GATT server interface. - * @return N/A. - */ - -void BLEService::executeCreate(BLEServer *pServer) { - //ESP_LOGD(LOG_TAG, ">> executeCreate() - Creating service (esp_ble_gatts_create_service) service uuid: %s", getUUID().toString().c_str()); - //getUUID(); // Needed for a weird bug fix - //char x[1000]; - //memcpy(x, &m_uuid, sizeof(m_uuid)); - //char x[10]; - //memcpy(x, &deleteMe, 10); - m_pServer = pServer; - m_semaphoreCreateEvt.take("executeCreate"); // Take the mutex and release at event ESP_GATTS_CREATE_EVT - - esp_gatt_srvc_id_t srvc_id; - srvc_id.is_primary = true; - srvc_id.id.inst_id = m_id; - srvc_id.id.uuid = *m_uuid.getNative(); - esp_err_t errRc = ::esp_ble_gatts_create_service( - getServer()->getGattsIf(), - &srvc_id, - m_numHandles // The maximum number of handles associated with the service. - ); - - if (errRc != ESP_OK) { - ESP_LOGE(LOG_TAG, "esp_ble_gatts_create_service: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return; - } - - m_semaphoreCreateEvt.wait("executeCreate"); - ESP_LOGD(LOG_TAG, "<< executeCreate"); -} // executeCreate - - -/** - * @brief Delete the service. - * Delete the service. - * @return N/A. - */ - -void BLEService::executeDelete() { - ESP_LOGD(LOG_TAG, ">> executeDelete()"); - m_semaphoreDeleteEvt.take("executeDelete"); // Take the mutex and release at event ESP_GATTS_DELETE_EVT - - esp_err_t errRc = ::esp_ble_gatts_delete_service( getHandle() ); - - if (errRc != ESP_OK) { - ESP_LOGE(LOG_TAG, "esp_ble_gatts_delete_service: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return; - } - - m_semaphoreDeleteEvt.wait("executeDelete"); - ESP_LOGD(LOG_TAG, "<< executeDelete"); -} // executeDelete - - -/** - * @brief Dump details of this BLE GATT service. - * @return N/A. - */ -void BLEService::dump() { - ESP_LOGD(LOG_TAG, "Service: uuid:%s, handle: 0x%.2x", - m_uuid.toString().c_str(), - m_handle); - ESP_LOGD(LOG_TAG, "Characteristics:\n%s", m_characteristicMap.toString().c_str()); -} // dump - - -/** - * @brief Get the UUID of the service. - * @return the UUID of the service. - */ -BLEUUID BLEService::getUUID() { - return m_uuid; -} // getUUID - - -/** - * @brief Start the service. - * Here we wish to start the service which means that we will respond to partner requests about it. - * Starting a service also means that we can create the corresponding characteristics. - * @return Start the service. - */ -void BLEService::start() { -// We ask the BLE runtime to start the service and then create each of the characteristics. -// We start the service through its local handle which was returned in the ESP_GATTS_CREATE_EVT event -// obtained as a result of calling esp_ble_gatts_create_service(). -// - ESP_LOGD(LOG_TAG, ">> start(): Starting service (esp_ble_gatts_start_service): %s", toString().c_str()); - if (m_handle == NULL_HANDLE) { - ESP_LOGE(LOG_TAG, "<< !!! We attempted to start a service but don't know its handle!"); - return; - } - - - BLECharacteristic *pCharacteristic = m_characteristicMap.getFirst(); - - while(pCharacteristic != nullptr) { - m_lastCreatedCharacteristic = pCharacteristic; - pCharacteristic->executeCreate(this); - - pCharacteristic = m_characteristicMap.getNext(); - } - // Start each of the characteristics ... these are found in the m_characteristicMap. - - m_semaphoreStartEvt.take("start"); - esp_err_t errRc = ::esp_ble_gatts_start_service(m_handle); - - if (errRc != ESP_OK) { - ESP_LOGE(LOG_TAG, "<< esp_ble_gatts_start_service: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return; - } - m_semaphoreStartEvt.wait("start"); - - ESP_LOGD(LOG_TAG, "<< start()"); -} // start - - -/** - * @brief Stop the service. - * @return Stop the service. - */ -void BLEService::stop() { -// We ask the BLE runtime to start the service and then create each of the characteristics. -// We start the service through its local handle which was returned in the ESP_GATTS_CREATE_EVT event -// obtained as a result of calling esp_ble_gatts_create_service(). -// - ESP_LOGD(LOG_TAG, ">> stop(): Stopping service (esp_ble_gatts_stop_service): %s", toString().c_str()); - if (m_handle == NULL_HANDLE) { - ESP_LOGE(LOG_TAG, "<< !!! We attempted to stop a service but don't know its handle!"); - return; - } - - m_semaphoreStopEvt.take("stop"); - esp_err_t errRc = ::esp_ble_gatts_stop_service(m_handle); - - if (errRc != ESP_OK) { - ESP_LOGE(LOG_TAG, "<< esp_ble_gatts_stop_service: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return; - } - m_semaphoreStopEvt.wait("stop"); - - ESP_LOGD(LOG_TAG, "<< stop()"); -} // start - - -/** - * @brief Set the handle associated with this service. - * @param [in] handle The handle associated with the service. - */ -void BLEService::setHandle(uint16_t handle) { - ESP_LOGD(LOG_TAG, ">> setHandle - Handle=0x%.2x, service UUID=%s)", handle, getUUID().toString().c_str()); - if (m_handle != NULL_HANDLE) { - ESP_LOGE(LOG_TAG, "!!! Handle is already set %.2x", m_handle); - return; - } - m_handle = handle; - ESP_LOGD(LOG_TAG, "<< setHandle"); -} // setHandle - - -/** - * @brief Get the handle associated with this service. - * @return The handle associated with this service. - */ -uint16_t BLEService::getHandle() { - return m_handle; -} // getHandle - - -/** - * @brief Add a characteristic to the service. - * @param [in] pCharacteristic A pointer to the characteristic to be added. - */ -void BLEService::addCharacteristic(BLECharacteristic* pCharacteristic) { -// We maintain a mapping of characteristics owned by this service. These are managed by the -// BLECharacteristicMap class instance found in m_characteristicMap. We add the characteristic -// to the map and then ask the service to add the characteristic at the BLE level (ESP-IDF). -// - ESP_LOGD(LOG_TAG, ">> addCharacteristic()"); - ESP_LOGD(LOG_TAG, "Adding characteristic: uuid=%s to service: %s", - pCharacteristic->getUUID().toString().c_str(), - toString().c_str()); - - // Check that we don't add the same characteristic twice. - if (m_characteristicMap.getByUUID(pCharacteristic->getUUID()) != nullptr) { - ESP_LOGW(LOG_TAG, "<< Adding a new characteristic with the same UUID as a previous one"); - //return; - } - - // Remember this characteristic in our map of characteristics. At this point, we can lookup by UUID - // but not by handle. The handle is allocated to us on the ESP_GATTS_ADD_CHAR_EVT. - m_characteristicMap.setByUUID(pCharacteristic, pCharacteristic->getUUID()); - - ESP_LOGD(LOG_TAG, "<< addCharacteristic()"); -} // addCharacteristic - - -/** - * @brief Create a new BLE Characteristic associated with this service. - * @param [in] uuid - The UUID of the characteristic. - * @param [in] properties - The properties of the characteristic. - * @return The new BLE characteristic. - */ -BLECharacteristic* BLEService::createCharacteristic(const char* uuid, uint32_t properties) { - return createCharacteristic(BLEUUID(uuid), properties); -} - - -/** - * @brief Create a new BLE Characteristic associated with this service. - * @param [in] uuid - The UUID of the characteristic. - * @param [in] properties - The properties of the characteristic. - * @return The new BLE characteristic. - */ -BLECharacteristic* BLEService::createCharacteristic(BLEUUID uuid, uint32_t properties) { - BLECharacteristic *pCharacteristic = new BLECharacteristic(uuid, properties); - addCharacteristic(pCharacteristic); - return pCharacteristic; -} // createCharacteristic - - -/** - * @brief Handle a GATTS server event. - */ -void BLEService::handleGATTServerEvent( - esp_gatts_cb_event_t event, - esp_gatt_if_t gatts_if, - esp_ble_gatts_cb_param_t *param) { - - - switch(event) { - // ESP_GATTS_ADD_CHAR_EVT - Indicate that a characteristic was added to the service. - // add_char: - // - esp_gatt_status_t status - // - uint16_t attr_handle - // - uint16_t service_handle - // - esp_bt_uuid_t char_uuid - - // If we have reached the correct service, then locate the characteristic and remember the handle - // for that characteristic. - case ESP_GATTS_ADD_CHAR_EVT: { - if (m_handle == param->add_char.service_handle) { - BLECharacteristic *pCharacteristic = getLastCreatedCharacteristic(); - if (pCharacteristic == nullptr) { - ESP_LOGE(LOG_TAG, "Expected to find characteristic with UUID: %s, but didnt!", - BLEUUID(param->add_char.char_uuid).toString().c_str()); - dump(); - break; - } - pCharacteristic->setHandle(param->add_char.attr_handle); - m_characteristicMap.setByHandle(param->add_char.attr_handle, pCharacteristic); - //ESP_LOGD(tag, "Characteristic map: %s", m_characteristicMap.toString().c_str()); - break; - } // Reached the correct service. - break; - } // ESP_GATTS_ADD_CHAR_EVT - - - // ESP_GATTS_START_EVT - // - // start: - // esp_gatt_status_t status - // uint16_t service_handle - case ESP_GATTS_START_EVT: { - if (param->start.service_handle == getHandle()) { - m_semaphoreStartEvt.give(); - } - break; - } // ESP_GATTS_START_EVT - - // ESP_GATTS_STOP_EVT - // - // stop: - // esp_gatt_status_t status - // uint16_t service_handle - // - case ESP_GATTS_STOP_EVT: { - if (param->stop.service_handle == getHandle()) { - m_semaphoreStopEvt.give(); - } - break; - } // ESP_GATTS_STOP_EVT - - - // ESP_GATTS_CREATE_EVT - // Called when a new service is registered as having been created. - // - // create: - // * esp_gatt_status_t status - // * uint16_t service_handle - // * esp_gatt_srvc_id_t service_id - // * - esp_gatt_id id - // * - esp_bt_uuid uuid - // * - uint8_t inst_id - // * - bool is_primary - // - case ESP_GATTS_CREATE_EVT: { - if (getUUID().equals(BLEUUID(param->create.service_id.id.uuid)) && m_id == param->create.service_id.id.inst_id) { - setHandle(param->create.service_handle); - m_semaphoreCreateEvt.give(); - } - break; - } // ESP_GATTS_CREATE_EVT - - - // ESP_GATTS_DELETE_EVT - // Called when a service is deleted. - // - // delete: - // * esp_gatt_status_t status - // * uint16_t service_handle - // - case ESP_GATTS_DELETE_EVT: { - if (param->del.service_handle == getHandle()) { - m_semaphoreDeleteEvt.give(); - } - break; - } // ESP_GATTS_DELETE_EVT - - default: { - break; - } // Default - } // Switch - - // Invoke the GATTS handler in each of the associated characteristics. - m_characteristicMap.handleGATTServerEvent(event, gatts_if, param); -} // handleGATTServerEvent - - -BLECharacteristic* BLEService::getCharacteristic(const char* uuid) { - return getCharacteristic(BLEUUID(uuid)); -} - - -BLECharacteristic* BLEService::getCharacteristic(BLEUUID uuid) { - return m_characteristicMap.getByUUID(uuid); -} - - -/** - * @brief Return a string representation of this service. - * A service is defined by: - * * Its UUID - * * Its handle - * @return A string representation of this service. - */ -std::string BLEService::toString() { - std::stringstream stringStream; - stringStream << "UUID: " << getUUID().toString() << - ", handle: 0x" << std::hex << std::setfill('0') << std::setw(2) << getHandle(); - return stringStream.str(); -} // toString - - -/** - * @brief Get the last created characteristic. - * It is lamentable that this function has to exist. It returns the last created characteristic. - * We need this because the descriptor API is built around the notion that a new descriptor, when created, - * is associated with the last characteristics created and we need that information. - * @return The last created characteristic. - */ -BLECharacteristic* BLEService::getLastCreatedCharacteristic() { - return m_lastCreatedCharacteristic; -} // getLastCreatedCharacteristic - - -/** - * @brief Get the BLE server associated with this service. - * @return The BLEServer associated with this service. - */ -BLEServer* BLEService::getServer() { - return m_pServer; -} // getServer - -#endif // CONFIG_BT_ENABLED diff --git a/lib/ESP32_BLE_Arduino/src/BLEService.h b/lib/ESP32_BLE_Arduino/src/BLEService.h deleted file mode 100644 index 93b4b2c6..00000000 --- a/lib/ESP32_BLE_Arduino/src/BLEService.h +++ /dev/null @@ -1,104 +0,0 @@ -/* - * BLEService.h - * - * Created on: Mar 25, 2017 - * Author: kolban - */ - -#ifndef COMPONENTS_CPP_UTILS_BLESERVICE_H_ -#define COMPONENTS_CPP_UTILS_BLESERVICE_H_ -#include "sdkconfig.h" -#if defined(CONFIG_BT_ENABLED) - -#include - -#include "BLECharacteristic.h" -#include "BLEServer.h" -#include "BLEUUID.h" -#include "FreeRTOS.h" - -class BLEServer; - -/** - * @brief A data mapping used to manage the set of %BLE characteristics known to the server. - */ -class BLECharacteristicMap { -public: - void setByUUID(BLECharacteristic* pCharacteristic, const char* uuid); - void setByUUID(BLECharacteristic* pCharacteristic, BLEUUID uuid); - void setByHandle(uint16_t handle, BLECharacteristic* pCharacteristic); - BLECharacteristic* getByUUID(const char* uuid); - BLECharacteristic* getByUUID(BLEUUID uuid); - BLECharacteristic* getByHandle(uint16_t handle); - BLECharacteristic* getFirst(); - BLECharacteristic* getNext(); - std::string toString(); - void handleGATTServerEvent( - esp_gatts_cb_event_t event, - esp_gatt_if_t gatts_if, - esp_ble_gatts_cb_param_t* param); - - -private: - std::map m_uuidMap; - std::map m_handleMap; - std::map::iterator m_iterator; -}; - - -/** - * @brief The model of a %BLE service. - * - */ -class BLEService { -public: - void addCharacteristic(BLECharacteristic* pCharacteristic); - BLECharacteristic* createCharacteristic(const char* uuid, uint32_t properties); - BLECharacteristic* createCharacteristic(BLEUUID uuid, uint32_t properties); - void dump(); - void executeCreate(BLEServer* pServer); - void executeDelete(); - BLECharacteristic* getCharacteristic(const char* uuid); - BLECharacteristic* getCharacteristic(BLEUUID uuid); - BLEUUID getUUID(); - BLEServer* getServer(); - void start(); - void stop(); - std::string toString(); - uint16_t getHandle(); - uint8_t m_id = 0; - -private: - BLEService(const char* uuid, uint32_t numHandles); - BLEService(BLEUUID uuid, uint32_t numHandles); - friend class BLEServer; - friend class BLEServiceMap; - friend class BLEDescriptor; - friend class BLECharacteristic; - friend class BLEDevice; - - BLECharacteristicMap m_characteristicMap; - uint16_t m_handle; - BLECharacteristic* m_lastCreatedCharacteristic; - BLEServer* m_pServer; - BLEUUID m_uuid; - - FreeRTOS::Semaphore m_semaphoreCreateEvt = FreeRTOS::Semaphore("CreateEvt"); - FreeRTOS::Semaphore m_semaphoreDeleteEvt = FreeRTOS::Semaphore("DeleteEvt"); - FreeRTOS::Semaphore m_semaphoreStartEvt = FreeRTOS::Semaphore("StartEvt"); - FreeRTOS::Semaphore m_semaphoreStopEvt = FreeRTOS::Semaphore("StopEvt"); - - uint32_t m_numHandles; - - BLECharacteristic* getLastCreatedCharacteristic(); - void handleGATTServerEvent( - esp_gatts_cb_event_t event, - esp_gatt_if_t gatts_if, - esp_ble_gatts_cb_param_t* param); - void setHandle(uint16_t handle); - //void setService(esp_gatt_srvc_id_t srvc_id); -}; // BLEService - - -#endif // CONFIG_BT_ENABLED -#endif /* COMPONENTS_CPP_UTILS_BLESERVICE_H_ */ diff --git a/lib/ESP32_BLE_Arduino/src/BLEServiceMap.cpp b/lib/ESP32_BLE_Arduino/src/BLEServiceMap.cpp deleted file mode 100644 index dd828fae..00000000 --- a/lib/ESP32_BLE_Arduino/src/BLEServiceMap.cpp +++ /dev/null @@ -1,132 +0,0 @@ -/* - * BLEServiceMap.cpp - * - * Created on: Jun 22, 2017 - * Author: kolban - */ -#include "sdkconfig.h" -#if defined(CONFIG_BT_ENABLED) -#include -#include -#include "BLEService.h" - - -/** - * @brief Return the service by UUID. - * @param [in] UUID The UUID to look up the service. - * @return The characteristic. - */ -BLEService* BLEServiceMap::getByUUID(const char* uuid) { - return getByUUID(BLEUUID(uuid)); -} - -/** - * @brief Return the service by UUID. - * @param [in] UUID The UUID to look up the service. - * @return The characteristic. - */ -BLEService* BLEServiceMap::getByUUID(BLEUUID uuid) { - for (auto &myPair : m_uuidMap) { - if (myPair.first->getUUID().equals(uuid)) { - return myPair.first; - } - } - //return m_uuidMap.at(uuid.toString()); - return nullptr; -} // getByUUID - - -/** - * @brief Return the service by handle. - * @param [in] handle The handle to look up the service. - * @return The service. - */ -BLEService* BLEServiceMap::getByHandle(uint16_t handle) { - return m_handleMap.at(handle); -} // getByHandle - - -/** - * @brief Set the service by UUID. - * @param [in] uuid The uuid of the service. - * @param [in] characteristic The service to cache. - * @return N/A. - */ -void BLEServiceMap::setByUUID(BLEUUID uuid, - BLEService *service) { - m_uuidMap.insert(std::pair(service, uuid.toString())); -} // setByUUID - - -/** - * @brief Set the service by handle. - * @param [in] handle The handle of the service. - * @param [in] service The service to cache. - * @return N/A. - */ -void BLEServiceMap::setByHandle(uint16_t handle, - BLEService* service) { - m_handleMap.insert(std::pair(handle, service)); -} // setByHandle - - -/** - * @brief Return a string representation of the service map. - * @return A string representation of the service map. - */ -std::string BLEServiceMap::toString() { - std::stringstream stringStream; - stringStream << std::hex << std::setfill('0'); - for (auto &myPair: m_handleMap) { - stringStream << "handle: 0x" << std::setw(2) << myPair.first << ", uuid: " + myPair.second->getUUID().toString() << "\n"; - } - return stringStream.str(); -} // toString - -void BLEServiceMap::handleGATTServerEvent( - esp_gatts_cb_event_t event, - esp_gatt_if_t gatts_if, - esp_ble_gatts_cb_param_t *param) { - // Invoke the handler for every Service we have. - for (auto &myPair : m_uuidMap) { - myPair.first->handleGATTServerEvent(event, gatts_if, param); - } -} - -/** - * @brief Get the first service in the map. - * @return The first service in the map. - */ -BLEService* BLEServiceMap::getFirst() { - m_iterator = m_uuidMap.begin(); - if (m_iterator == m_uuidMap.end()) { - return nullptr; - } - BLEService* pRet = m_iterator->first; - m_iterator++; - return pRet; -} // getFirst - -/** - * @brief Get the next service in the map. - * @return The next service in the map. - */ -BLEService* BLEServiceMap::getNext() { - if (m_iterator == m_uuidMap.end()) { - return nullptr; - } - BLEService* pRet = m_iterator->first; - m_iterator++; - return pRet; -} // getNext - -/** - * @brief Removes service from maps. - * @return N/A. - */ -void BLEServiceMap::removeService(BLEService *service){ - m_handleMap.erase(service->getHandle()); - m_uuidMap.erase(service); -} // removeService - -#endif /* CONFIG_BT_ENABLED */ diff --git a/lib/ESP32_BLE_Arduino/src/BLEUUID.cpp b/lib/ESP32_BLE_Arduino/src/BLEUUID.cpp deleted file mode 100644 index 9ca7cdd7..00000000 --- a/lib/ESP32_BLE_Arduino/src/BLEUUID.cpp +++ /dev/null @@ -1,410 +0,0 @@ -/* - * BLEUUID.cpp - * - * Created on: Jun 21, 2017 - * Author: kolban - */ -#include "sdkconfig.h" -#if defined(CONFIG_BT_ENABLED) -#include -#include -#include -#include -#include -#include -#include -#include "BLEUUID.h" -static const char* LOG_TAG = "BLEUUID"; - -#ifdef ARDUINO_ARCH_ESP32 -#include "esp32-hal-log.h" -#endif - -/** - * @brief Copy memory from source to target but in reverse order. - * - * When we move memory from one location it is normally: - * - * ``` - * [0][1][2]...[n] -> [0][1][2]...[n] - * ``` - * - * with this function, it is: - * - * ``` - * [0][1][2]...[n] -> [n][n-1][n-2]...[0] - * ``` - * - * @param [in] target The target of the copy - * @param [in] source The source of the copy - * @param [in] size The number of bytes to copy - */ -static void memrcpy(uint8_t* target, uint8_t* source, uint32_t size) { - assert(size > 0); - target+=(size-1); // Point target to the last byte of the target data - while (size > 0) { - *target = *source; - target--; - source++; - size--; - } -} // memrcpy - - -/** - * @brief Create a UUID from a string. - * - * Create a UUID from a string. There will be two possible stories here. Either the string represents - * a binary data field or the string represents a hex encoding of a UUID. - * For the hex encoding, here is an example: - * - * ``` - * "beb5483e-36e1-4688-b7f5-ea07361b26a8" - * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 - * 12345678-90ab-cdef-1234-567890abcdef - * ``` - * - * This has a length of 36 characters. We need to parse this into 16 bytes. - * - * @param [in] value The string to build a UUID from. - */ -BLEUUID::BLEUUID(std::string value) { - m_valueSet = true; - if (value.length() == 2) { - m_uuid.len = ESP_UUID_LEN_16; - m_uuid.uuid.uuid16 = value[0] | (value[1] << 8); - } - else if (value.length() == 4) { - m_uuid.len = ESP_UUID_LEN_32; - m_uuid.uuid.uuid32 = value[0] | (value[1] << 8) | (value[2] << 16) | (value[3] << 24); - } - else if (value.length() == 16) { - m_uuid.len = ESP_UUID_LEN_128; - memrcpy(m_uuid.uuid.uuid128, (uint8_t*)value.data(), 16); - } - else if (value.length() == 36) { -// If the length of the string is 36 bytes then we will assume it is a long hex string in -// UUID format. - m_uuid.len = ESP_UUID_LEN_128; - int vals[16]; - sscanf(value.c_str(), "%2x%2x%2x%2x-%2x%2x-%2x%2x-%2x%2x-%2x%2x%2x%2x%2x%2x", - &vals[15], - &vals[14], - &vals[13], - &vals[12], - &vals[11], - &vals[10], - &vals[9], - &vals[8], - &vals[7], - &vals[6], - &vals[5], - &vals[4], - &vals[3], - &vals[2], - &vals[1], - &vals[0] - ); - - int i; - for (i=0; i<16; i++) { - m_uuid.uuid.uuid128[i] = vals[i]; - } - } - else { - ESP_LOGE(LOG_TAG, "ERROR: UUID value not 2, 4, 16 or 36 bytes"); - m_valueSet = false; - } -} //BLEUUID(std::string) - - -/** - * @brief Create a UUID from 16 bytes of memory. - * - * @param [in] pData The pointer to the start of the UUID. - * @param [in] size The size of the data. - * @param [in] msbFirst Is the MSB first in pData memory? - */ -BLEUUID::BLEUUID(uint8_t* pData, size_t size, bool msbFirst) { - if (size != 16) { - ESP_LOGE(LOG_TAG, "ERROR: UUID length not 16 bytes"); - return; - } - m_uuid.len = ESP_UUID_LEN_128; - if (msbFirst) { - memrcpy(m_uuid.uuid.uuid128, pData, 16); - } else { - memcpy(m_uuid.uuid.uuid128, pData, 16); - } - m_valueSet = true; -} // BLEUUID - - -/** - * @brief Create a UUID from the 16bit value. - * - * @param [in] uuid The 16bit short form UUID. - */ -BLEUUID::BLEUUID(uint16_t uuid) { - m_uuid.len = ESP_UUID_LEN_16; - m_uuid.uuid.uuid16 = uuid; - m_valueSet = true; - -} // BLEUUID - - -/** - * @brief Create a UUID from the 32bit value. - * - * @param [in] uuid The 32bit short form UUID. - */ -BLEUUID::BLEUUID(uint32_t uuid) { - m_uuid.len = ESP_UUID_LEN_32; - m_uuid.uuid.uuid32 = uuid; - m_valueSet = true; -} // BLEUUID - - -/** - * @brief Create a UUID from the native UUID. - * - * @param [in] uuid The native UUID. - */ -BLEUUID::BLEUUID(esp_bt_uuid_t uuid) { - m_uuid = uuid; - m_valueSet = true; -} // BLEUUID - - -/** - * @brief Create a UUID from the ESP32 esp_gat_id_t. - * - * @param [in] gattId The data to create the UUID from. - */ -BLEUUID::BLEUUID(esp_gatt_id_t gattId) : BLEUUID(gattId.uuid) { -} // BLEUUID - - -BLEUUID::BLEUUID() { - m_valueSet = false; -} // BLEUUID - - -/** - * @brief Get the number of bits in this uuid. - * @return The number of bits in the UUID. One of 16, 32 or 128. - */ -int BLEUUID::bitSize() { - if (m_valueSet == false) { - return 0; - } - switch(m_uuid.len) { - case ESP_UUID_LEN_16: { - return 16; - } - case ESP_UUID_LEN_32: { - return 32; - } - case ESP_UUID_LEN_128: { - return 128; - } - default: { - ESP_LOGE(LOG_TAG, "Unknown UUID length: %d", m_uuid.len); - return 0; - } - } // End of switch -} // bitSize - - -/** - * @brief Compare a UUID against this UUID. - * - * @param [in] uuid The UUID to compare against. - * @return True if the UUIDs are equal and false otherwise. - */ -bool BLEUUID::equals(BLEUUID uuid) { - //ESP_LOGD(TAG, "Comparing: %s to %s", toString().c_str(), uuid.toString().c_str()); - if (m_valueSet == false || uuid.m_valueSet == false) { - return false; - } - - if (uuid.m_uuid.len != m_uuid.len) { - return uuid.toString() == toString(); - } - - if (uuid.m_uuid.len == ESP_UUID_LEN_16) { - return uuid.m_uuid.uuid.uuid16 == m_uuid.uuid.uuid16; - } - - if (uuid.m_uuid.len == ESP_UUID_LEN_32) { - return uuid.m_uuid.uuid.uuid32 == m_uuid.uuid.uuid32; - } - - return memcmp(uuid.m_uuid.uuid.uuid128, m_uuid.uuid.uuid128, 16) == 0; -} // equals - - -/** - * Create a BLEUUID from a string of the form: - * 0xNNNN - * 0xNNNNNNNN - * 0x - * NNNN - * NNNNNNNN - * - */ -BLEUUID BLEUUID::fromString(std::string _uuid){ - uint8_t start = 0; - if (strstr(_uuid.c_str(), "0x") != nullptr) { // If the string starts with 0x, skip those characters. - start = 2; - } - uint8_t len = _uuid.length() - start; // Calculate the length of the string we are going to use. - - if( len == 4) { - uint16_t x = strtoul(_uuid.substr(start, len).c_str(), NULL, 16); - return BLEUUID(x); - } else if (len == 8) { - uint32_t x = strtoul(_uuid.substr(start, len).c_str(), NULL, 16); - return BLEUUID(x); - } else if (len == 36) { - return BLEUUID(_uuid); - } - return BLEUUID(); -} // fromString - - -/** - * @brief Get the native UUID value. - * - * @return The native UUID value or NULL if not set. - */ -esp_bt_uuid_t* BLEUUID::getNative() { - //ESP_LOGD(TAG, ">> getNative()") - if (m_valueSet == false) { - ESP_LOGD(LOG_TAG, "<< Return of un-initialized UUID!"); - return nullptr; - } - //ESP_LOGD(TAG, "<< getNative()"); - return &m_uuid; -} // getNative - - -/** - * @brief Convert a UUID to its 128 bit representation. - * - * A UUID can be internally represented as 16bit, 32bit or the full 128bit. This method - * will convert 16 or 32 bit representations to the full 128bit. - */ -BLEUUID BLEUUID::to128() { - //ESP_LOGD(LOG_TAG, ">> toFull() - %s", toString().c_str()); - - // If we either don't have a value or are already a 128 bit UUID, nothing further to do. - if (m_valueSet == false || m_uuid.len == ESP_UUID_LEN_128) { - return *this; - } - - // If we are 16 bit or 32 bit, then set the 4 bytes of the variable part of the UUID. - if (m_uuid.len == ESP_UUID_LEN_16) { - uint16_t temp = m_uuid.uuid.uuid16; - m_uuid.uuid.uuid128[15] = 0; - m_uuid.uuid.uuid128[14] = 0; - m_uuid.uuid.uuid128[13] = (temp >> 8) & 0xff; - m_uuid.uuid.uuid128[12] = temp & 0xff; - - } - else if (m_uuid.len == ESP_UUID_LEN_32) { - uint32_t temp = m_uuid.uuid.uuid32; - m_uuid.uuid.uuid128[15] = (temp >> 24) & 0xff; - m_uuid.uuid.uuid128[14] = (temp >> 16) & 0xff; - m_uuid.uuid.uuid128[13] = (temp >> 8) & 0xff; - m_uuid.uuid.uuid128[12] = temp & 0xff; - } - - // Set the fixed parts of the UUID. - m_uuid.uuid.uuid128[11] = 0x00; - m_uuid.uuid.uuid128[10] = 0x00; - - m_uuid.uuid.uuid128[9] = 0x10; - m_uuid.uuid.uuid128[8] = 0x00; - - m_uuid.uuid.uuid128[7] = 0x80; - m_uuid.uuid.uuid128[6] = 0x00; - - m_uuid.uuid.uuid128[5] = 0x00; - m_uuid.uuid.uuid128[4] = 0x80; - m_uuid.uuid.uuid128[3] = 0x5f; - m_uuid.uuid.uuid128[2] = 0x9b; - m_uuid.uuid.uuid128[1] = 0x34; - m_uuid.uuid.uuid128[0] = 0xfb; - - m_uuid.len = ESP_UUID_LEN_128; - //ESP_LOGD(TAG, "<< toFull <- %s", toString().c_str()); - return *this; -} // to128 - - - - -/** - * @brief Get a string representation of the UUID. - * - * The format of a string is: - * 01234567 8901 2345 6789 012345678901 - * 0000180d-0000-1000-8000-00805f9b34fb - * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 - * - * @return A string representation of the UUID. - */ -std::string BLEUUID::toString() { - if (m_valueSet == false) { // If we have no value, nothing to format. - return ""; - } - - // If the UUIDs are 16 or 32 bit, pad correctly. - std::stringstream ss; - - if (m_uuid.len == ESP_UUID_LEN_16) { // If the UUID is 16bit, pad correctly. - ss << "0000" << - std::hex << - std::setfill('0') << - std::setw(4) << - m_uuid.uuid.uuid16 << - "-0000-1000-8000-00805f9b34fb"; - return ss.str(); // Return the string - } // End 16bit UUID - - if (m_uuid.len == ESP_UUID_LEN_32) { // If the UUID is 32bit, pad correctly. - ss << std::hex << - std::setfill('0') << - std::setw(8) << - m_uuid.uuid.uuid32 << - "-0000-1000-8000-00805f9b34fb"; - return ss.str(); // return the string - } // End 32bit UUID - - // The UUID is not 16bit or 32bit which means that it is 128bit. - // - // UUID string format: - // AABBCCDD-EEFF-GGHH-IIJJ-KKLLMMNNOOPP - // - ss << std::hex << std::setfill('0') << - std::setw(2) << (int)m_uuid.uuid.uuid128[15] << - std::setw(2) << (int)m_uuid.uuid.uuid128[14] << - std::setw(2) << (int)m_uuid.uuid.uuid128[13] << - std::setw(2) << (int)m_uuid.uuid.uuid128[12] << "-" << - std::setw(2) << (int)m_uuid.uuid.uuid128[11] << - std::setw(2) << (int)m_uuid.uuid.uuid128[10] << "-" << - std::setw(2) << (int)m_uuid.uuid.uuid128[9] << - std::setw(2) << (int)m_uuid.uuid.uuid128[8] << "-" << - std::setw(2) << (int)m_uuid.uuid.uuid128[7] << - std::setw(2) << (int)m_uuid.uuid.uuid128[6] << "-" << - std::setw(2) << (int)m_uuid.uuid.uuid128[5] << - std::setw(2) << (int)m_uuid.uuid.uuid128[4] << - std::setw(2) << (int)m_uuid.uuid.uuid128[3] << - std::setw(2) << (int)m_uuid.uuid.uuid128[2] << - std::setw(2) << (int)m_uuid.uuid.uuid128[1] << - std::setw(2) << (int)m_uuid.uuid.uuid128[0]; - return ss.str(); -} // toString - -#endif /* CONFIG_BT_ENABLED */ diff --git a/lib/ESP32_BLE_Arduino/src/BLEUUID.h b/lib/ESP32_BLE_Arduino/src/BLEUUID.h deleted file mode 100644 index 5fb7795b..00000000 --- a/lib/ESP32_BLE_Arduino/src/BLEUUID.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - * BLEUUID.h - * - * Created on: Jun 21, 2017 - * Author: kolban - */ - -#ifndef COMPONENTS_CPP_UTILS_BLEUUID_H_ -#define COMPONENTS_CPP_UTILS_BLEUUID_H_ -#include "sdkconfig.h" -#if defined(CONFIG_BT_ENABLED) -#include -#include - -/** - * @brief A model of a %BLE UUID. - */ -class BLEUUID { -public: - BLEUUID(std::string uuid); - BLEUUID(uint16_t uuid); - BLEUUID(uint32_t uuid); - BLEUUID(esp_bt_uuid_t uuid); - BLEUUID(uint8_t* pData, size_t size, bool msbFirst); - BLEUUID(esp_gatt_id_t gattId); - BLEUUID(); - int bitSize(); // Get the number of bits in this uuid. - bool equals(BLEUUID uuid); - esp_bt_uuid_t* getNative(); - BLEUUID to128(); - std::string toString(); - static BLEUUID fromString(std::string uuid); // Create a BLEUUID from a string - -private: - esp_bt_uuid_t m_uuid; // The underlying UUID structure that this class wraps. - bool m_valueSet; // Is there a value set for this instance. -}; // BLEUUID -#endif /* CONFIG_BT_ENABLED */ -#endif /* COMPONENTS_CPP_UTILS_BLEUUID_H_ */ diff --git a/lib/ESP32_BLE_Arduino/src/BLEUtils.cpp b/lib/ESP32_BLE_Arduino/src/BLEUtils.cpp deleted file mode 100644 index a33ee27a..00000000 --- a/lib/ESP32_BLE_Arduino/src/BLEUtils.cpp +++ /dev/null @@ -1,2172 +0,0 @@ -/* - * BLEUtils.cpp - * - * Created on: Mar 25, 2017 - * Author: kolban - */ -#include "sdkconfig.h" -#if defined(CONFIG_BT_ENABLED) -#include "BLEAddress.h" -#include "BLEClient.h" -#include "BLEUtils.h" -#include "BLEUUID.h" -#include "GeneralUtils.h" - -#include -#include -#include // ESP32 BLE -#include // ESP32 BLE -#include // ESP32 BLE -#include // ESP32 BLE -#include // ESP32 ESP-IDF -#include // ESP32 ESP-IDF -#include // Part of C++ STL -#include -#include - -#ifdef ARDUINO_ARCH_ESP32 -#include "esp32-hal-log.h" -#endif - -static const char* LOG_TAG = "BLEUtils"; // Tag for logging. - -/* -static std::map g_addressMap; -static std::map g_connIdMap; -*/ - -typedef struct { - uint32_t assignedNumber; - const char* name; -} member_t; - -static const member_t members_ids[] = { - {0xFE08, "Microsoft"}, - {0xFE09, "Pillsy, Inc."}, - {0xFE0A, "ruwido austria gmbh"}, - {0xFE0B, "ruwido austria gmbh"}, - {0xFE0C, "Procter & Gamble"}, - {0xFE0D, "Procter & Gamble"}, - {0xFE0E, "Setec Pty Ltd"}, - {0xFE0F, "Philips Lighting B.V."}, - {0xFE10, "Lapis Semiconductor Co., Ltd."}, - {0xFE11, "GMC-I Messtechnik GmbH"}, - {0xFE12, "M-Way Solutions GmbH"}, - {0xFE13, "Apple Inc."}, - {0xFE14, "Flextronics International USA Inc."}, - {0xFE15, "Amazon Fulfillment Services, Inc."}, - {0xFE16, "Footmarks, Inc."}, - {0xFE17, "Telit Wireless Solutions GmbH"}, - {0xFE18, "Runtime, Inc."}, - {0xFE19, "Google Inc."}, - {0xFE1A, "Tyto Life LLC"}, - {0xFE1B, "Tyto Life LLC"}, - {0xFE1C, "NetMedia, Inc."}, - {0xFE1D, "Illuminati Instrument Corporation"}, - {0xFE1E, "Smart Innovations Co., Ltd"}, - {0xFE1F, "Garmin International, Inc."}, - {0xFE20, "Emerson"}, - {0xFE21, "Bose Corporation"}, - {0xFE22, "Zoll Medical Corporation"}, - {0xFE23, "Zoll Medical Corporation"}, - {0xFE24, "August Home Inc"}, - {0xFE25, "Apple, Inc. "}, - {0xFE26, "Google Inc."}, - {0xFE27, "Google Inc."}, - {0xFE28, "Ayla Networks"}, - {0xFE29, "Gibson Innovations"}, - {0xFE2A, "DaisyWorks, Inc."}, - {0xFE2B, "ITT Industries"}, - {0xFE2C, "Google Inc."}, - {0xFE2D, "SMART INNOVATION Co.,Ltd"}, - {0xFE2E, "ERi,Inc."}, - {0xFE2F, "CRESCO Wireless, Inc"}, - {0xFE30, "Volkswagen AG"}, - {0xFE31, "Volkswagen AG"}, - {0xFE32, "Pro-Mark, Inc."}, - {0xFE33, "CHIPOLO d.o.o."}, - {0xFE34, "SmallLoop LLC"}, - {0xFE35, "HUAWEI Technologies Co., Ltd"}, - {0xFE36, "HUAWEI Technologies Co., Ltd"}, - {0xFE37, "Spaceek LTD"}, - {0xFE38, "Spaceek LTD"}, - {0xFE39, "TTS Tooltechnic Systems AG & Co. KG"}, - {0xFE3A, "TTS Tooltechnic Systems AG & Co. KG"}, - {0xFE3B, "Dolby Laboratories"}, - {0xFE3C, "Alibaba"}, - {0xFE3D, "BD Medical"}, - {0xFE3E, "BD Medical"}, - {0xFE3F, "Friday Labs Limited"}, - {0xFE40, "Inugo Systems Limited"}, - {0xFE41, "Inugo Systems Limited"}, - {0xFE42, "Nets A/S "}, - {0xFE43, "Andreas Stihl AG & Co. KG"}, - {0xFE44, "SK Telecom "}, - {0xFE45, "Snapchat Inc"}, - {0xFE46, "B&O Play A/S "}, - {0xFE47, "General Motors"}, - {0xFE48, "General Motors"}, - {0xFE49, "SenionLab AB"}, - {0xFE4A, "OMRON HEALTHCARE Co., Ltd."}, - {0xFE4B, "Philips Lighting B.V."}, - {0xFE4C, "Volkswagen AG"}, - {0xFE4D, "Casambi Technologies Oy"}, - {0xFE4E, "NTT docomo"}, - {0xFE4F, "Molekule, Inc."}, - {0xFE50, "Google Inc."}, - {0xFE51, "SRAM"}, - {0xFE52, "SetPoint Medical"}, - {0xFE53, "3M"}, - {0xFE54, "Motiv, Inc."}, - {0xFE55, "Google Inc."}, - {0xFE56, "Google Inc."}, - {0xFE57, "Dotted Labs"}, - {0xFE58, "Nordic Semiconductor ASA"}, - {0xFE59, "Nordic Semiconductor ASA"}, - {0xFE5A, "Chronologics Corporation"}, - {0xFE5B, "GT-tronics HK Ltd"}, - {0xFE5C, "million hunters GmbH"}, - {0xFE5D, "Grundfos A/S"}, - {0xFE5E, "Plastc Corporation"}, - {0xFE5F, "Eyefi, Inc."}, - {0xFE60, "Lierda Science & Technology Group Co., Ltd."}, - {0xFE61, "Logitech International SA"}, - {0xFE62, "Indagem Tech LLC"}, - {0xFE63, "Connected Yard, Inc."}, - {0xFE64, "Siemens AG"}, - {0xFE65, "CHIPOLO d.o.o."}, - {0xFE66, "Intel Corporation"}, - {0xFE67, "Lab Sensor Solutions"}, - {0xFE68, "Qualcomm Life Inc"}, - {0xFE69, "Qualcomm Life Inc"}, - {0xFE6A, "Kontakt Micro-Location Sp. z o.o."}, - {0xFE6B, "TASER International, Inc."}, - {0xFE6C, "TASER International, Inc."}, - {0xFE6D, "The University of Tokyo"}, - {0xFE6E, "The University of Tokyo"}, - {0xFE6F, "LINE Corporation"}, - {0xFE70, "Beijing Jingdong Century Trading Co., Ltd."}, - {0xFE71, "Plume Design Inc"}, - {0xFE72, "St. Jude Medical, Inc."}, - {0xFE73, "St. Jude Medical, Inc."}, - {0xFE74, "unwire"}, - {0xFE75, "TangoMe"}, - {0xFE76, "TangoMe"}, - {0xFE77, "Hewlett-Packard Company"}, - {0xFE78, "Hewlett-Packard Company"}, - {0xFE79, "Zebra Technologies"}, - {0xFE7A, "Bragi GmbH"}, - {0xFE7B, "Orion Labs, Inc."}, - {0xFE7C, "Telit Wireless Solutions (Formerly Stollmann E+V GmbH)"}, - {0xFE7D, "Aterica Health Inc."}, - {0xFE7E, "Awear Solutions Ltd"}, - {0xFE7F, "Doppler Lab"}, - {0xFE80, "Doppler Lab"}, - {0xFE81, "Medtronic Inc."}, - {0xFE82, "Medtronic Inc."}, - {0xFE83, "Blue Bite"}, - {0xFE84, "RF Digital Corp"}, - {0xFE85, "RF Digital Corp"}, - {0xFE86, "HUAWEI Technologies Co., Ltd. ( )"}, - {0xFE87, "Qingdao Yeelink Information Technology Co., Ltd. ( )"}, - {0xFE88, "SALTO SYSTEMS S.L."}, - {0xFE89, "B&O Play A/S"}, - {0xFE8A, "Apple, Inc."}, - {0xFE8B, "Apple, Inc."}, - {0xFE8C, "TRON Forum"}, - {0xFE8D, "Interaxon Inc."}, - {0xFE8E, "ARM Ltd"}, - {0xFE8F, "CSR"}, - {0xFE90, "JUMA"}, - {0xFE91, "Shanghai Imilab Technology Co.,Ltd"}, - {0xFE92, "Jarden Safety & Security"}, - {0xFE93, "OttoQ Inc."}, - {0xFE94, "OttoQ Inc."}, - {0xFE95, "Xiaomi Inc."}, - {0xFE96, "Tesla Motor Inc."}, - {0xFE97, "Tesla Motor Inc."}, - {0xFE98, "Currant, Inc."}, - {0xFE99, "Currant, Inc."}, - {0xFE9A, "Estimote"}, - {0xFE9B, "Samsara Networks, Inc"}, - {0xFE9C, "GSI Laboratories, Inc."}, - {0xFE9D, "Mobiquity Networks Inc"}, - {0xFE9E, "Dialog Semiconductor B.V."}, - {0xFE9F, "Google Inc."}, - {0xFEA0, "Google Inc."}, - {0xFEA1, "Intrepid Control Systems, Inc."}, - {0xFEA2, "Intrepid Control Systems, Inc."}, - {0xFEA3, "ITT Industries"}, - {0xFEA4, "Paxton Access Ltd"}, - {0xFEA5, "GoPro, Inc."}, - {0xFEA6, "GoPro, Inc."}, - {0xFEA7, "UTC Fire and Security"}, - {0xFEA8, "Savant Systems LLC"}, - {0xFEA9, "Savant Systems LLC"}, - {0xFEAA, "Google Inc."}, - {0xFEAB, "Nokia Corporation"}, - {0xFEAC, "Nokia Corporation"}, - {0xFEAD, "Nokia Corporation"}, - {0xFEAE, "Nokia Corporation"}, - {0xFEAF, "Nest Labs Inc."}, - {0xFEB0, "Nest Labs Inc."}, - {0xFEB1, "Electronics Tomorrow Limited"}, - {0xFEB2, "Microsoft Corporation"}, - {0xFEB3, "Taobao"}, - {0xFEB4, "WiSilica Inc."}, - {0xFEB5, "WiSilica Inc."}, - {0xFEB6, "Vencer Co, Ltd"}, - {0xFEB7, "Facebook, Inc."}, - {0xFEB8, "Facebook, Inc."}, - {0xFEB9, "LG Electronics"}, - {0xFEBA, "Tencent Holdings Limited"}, - {0xFEBB, "adafruit industries"}, - {0xFEBC, "Dexcom, Inc. "}, - {0xFEBD, "Clover Network, Inc."}, - {0xFEBE, "Bose Corporation"}, - {0xFEBF, "Nod, Inc."}, - {0xFEC0, "KDDI Corporation"}, - {0xFEC1, "KDDI Corporation"}, - {0xFEC2, "Blue Spark Technologies, Inc."}, - {0xFEC3, "360fly, Inc."}, - {0xFEC4, "PLUS Location Systems"}, - {0xFEC5, "Realtek Semiconductor Corp."}, - {0xFEC6, "Kocomojo, LLC"}, - {0xFEC7, "Apple, Inc."}, - {0xFEC8, "Apple, Inc."}, - {0xFEC9, "Apple, Inc."}, - {0xFECA, "Apple, Inc."}, - {0xFECB, "Apple, Inc."}, - {0xFECC, "Apple, Inc."}, - {0xFECD, "Apple, Inc."}, - {0xFECE, "Apple, Inc."}, - {0xFECF, "Apple, Inc."}, - {0xFED0, "Apple, Inc."}, - {0xFED1, "Apple, Inc."}, - {0xFED2, "Apple, Inc."}, - {0xFED3, "Apple, Inc."}, - {0xFED4, "Apple, Inc."}, - {0xFED5, "Plantronics Inc."}, - {0xFED6, "Broadcom Corporation"}, - {0xFED7, "Broadcom Corporation"}, - {0xFED8, "Google Inc."}, - {0xFED9, "Pebble Technology Corporation"}, - {0xFEDA, "ISSC Technologies Corporation"}, - {0xFEDB, "Perka, Inc."}, - {0xFEDC, "Jawbone"}, - {0xFEDD, "Jawbone"}, - {0xFEDE, "Coin, Inc."}, - {0xFEDF, "Design SHIFT"}, - {0xFEE0, "Anhui Huami Information Technology Co."}, - {0xFEE1, "Anhui Huami Information Technology Co."}, - {0xFEE2, "Anki, Inc."}, - {0xFEE3, "Anki, Inc."}, - {0xFEE4, "Nordic Semiconductor ASA"}, - {0xFEE5, "Nordic Semiconductor ASA"}, - {0xFEE6, "Silvair, Inc."}, - {0xFEE7, "Tencent Holdings Limited"}, - {0xFEE8, "Quintic Corp."}, - {0xFEE9, "Quintic Corp."}, - {0xFEEA, "Swirl Networks, Inc."}, - {0xFEEB, "Swirl Networks, Inc."}, - {0xFEEC, "Tile, Inc."}, - {0xFEED, "Tile, Inc."}, - {0xFEEE, "Polar Electro Oy"}, - {0xFEEF, "Polar Electro Oy"}, - {0xFEF0, "Intel"}, - {0xFEF1, "CSR"}, - {0xFEF2, "CSR"}, - {0xFEF3, "Google Inc."}, - {0xFEF4, "Google Inc."}, - {0xFEF5, "Dialog Semiconductor GmbH"}, - {0xFEF6, "Wicentric, Inc."}, - {0xFEF7, "Aplix Corporation"}, - {0xFEF8, "Aplix Corporation"}, - {0xFEF9, "PayPal, Inc."}, - {0xFEFA, "PayPal, Inc."}, - {0xFEFB, "Telit Wireless Solutions (Formerly Stollmann E+V GmbH)"}, - {0xFEFC, "Gimbal, Inc."}, - {0xFEFD, "Gimbal, Inc."}, - {0xFEFE, "GN ReSound A/S"}, - {0xFEFF, "GN Netcom"}, - {0xFFFF, "Reserved"}, /*for testing purposes only*/ - {0, "" } -}; - -typedef struct { - uint32_t assignedNumber; - const char* name; -} gattdescriptor_t; - -static const gattdescriptor_t g_descriptor_ids[] = { - {0x2905,"Characteristic Aggregate Format"}, - {0x2900,"Characteristic Extended Properties"}, - {0x2904,"Characteristic Presentation Format"}, - {0x2901,"Characteristic User Description"}, - {0x2902,"Client Characteristic Configuration"}, - {0x290B,"Environmental Sensing Configuration"}, - {0x290C,"Environmental Sensing Measurement"}, - {0x290D,"Environmental Sensing Trigger Setting"}, - {0x2907,"External Report Reference"}, - {0x2909,"Number of Digitals"}, - {0x2908,"Report Reference"}, - {0x2903,"Server Characteristic Configuration"}, - {0x290E,"Time Trigger Setting"}, - {0x2906,"Valid Range"}, - {0x290A,"Value Trigger Setting"}, - { 0, "" } -}; - -typedef struct { - uint32_t assignedNumber; - const char* name; -} characteristicMap_t; - -static const characteristicMap_t g_characteristicsMappings[] = { - {0x2A7E,"Aerobic Heart Rate Lower Limit"}, - {0x2A84,"Aerobic Heart Rate Upper Limit"}, - {0x2A7F,"Aerobic Threshold"}, - {0x2A80,"Age"}, - {0x2A5A,"Aggregate"}, - {0x2A43,"Alert Category ID"}, - {0x2A42,"Alert Category ID Bit Mask"}, - {0x2A06,"Alert Level"}, - {0x2A44,"Alert Notification Control Point"}, - {0x2A3F,"Alert Status"}, - {0x2AB3,"Altitude"}, - {0x2A81,"Anaerobic Heart Rate Lower Limit"}, - {0x2A82,"Anaerobic Heart Rate Upper Limit"}, - {0x2A83,"Anaerobic Threshold"}, - {0x2A58,"Analog"}, - {0x2A59,"Analog Output"}, - {0x2A73,"Apparent Wind Direction"}, - {0x2A72,"Apparent Wind Speed"}, - {0x2A01,"Appearance"}, - {0x2AA3,"Barometric Pressure Trend"}, - {0x2A19,"Battery Level"}, - {0x2A1B,"Battery Level State"}, - {0x2A1A,"Battery Power State"}, - {0x2A49,"Blood Pressure Feature"}, - {0x2A35,"Blood Pressure Measurement"}, - {0x2A9B,"Body Composition Feature"}, - {0x2A9C,"Body Composition Measurement"}, - {0x2A38,"Body Sensor Location"}, - {0x2AA4,"Bond Management Control Point"}, - {0x2AA5,"Bond Management Features"}, - {0x2A22,"Boot Keyboard Input Report"}, - {0x2A32,"Boot Keyboard Output Report"}, - {0x2A33,"Boot Mouse Input Report"}, - {0x2AA6,"Central Address Resolution"}, - {0x2AA8,"CGM Feature"}, - {0x2AA7,"CGM Measurement"}, - {0x2AAB,"CGM Session Run Time"}, - {0x2AAA,"CGM Session Start Time"}, - {0x2AAC,"CGM Specific Ops Control Point"}, - {0x2AA9,"CGM Status"}, - {0x2ACE,"Cross Trainer Data"}, - {0x2A5C,"CSC Feature"}, - {0x2A5B,"CSC Measurement"}, - {0x2A2B,"Current Time"}, - {0x2A66,"Cycling Power Control Point"}, - {0x2A66,"Cycling Power Control Point"}, - {0x2A65,"Cycling Power Feature"}, - {0x2A65,"Cycling Power Feature"}, - {0x2A63,"Cycling Power Measurement"}, - {0x2A64,"Cycling Power Vector"}, - {0x2A99,"Database Change Increment"}, - {0x2A85,"Date of Birth"}, - {0x2A86,"Date of Threshold Assessment"}, - {0x2A08,"Date Time"}, - {0x2A0A,"Day Date Time"}, - {0x2A09,"Day of Week"}, - {0x2A7D,"Descriptor Value Changed"}, - {0x2A00,"Device Name"}, - {0x2A7B,"Dew Point"}, - {0x2A56,"Digital"}, - {0x2A57,"Digital Output"}, - {0x2A0D,"DST Offset"}, - {0x2A6C,"Elevation"}, - {0x2A87,"Email Address"}, - {0x2A0B,"Exact Time 100"}, - {0x2A0C,"Exact Time 256"}, - {0x2A88,"Fat Burn Heart Rate Lower Limit"}, - {0x2A89,"Fat Burn Heart Rate Upper Limit"}, - {0x2A26,"Firmware Revision String"}, - {0x2A8A,"First Name"}, - {0x2AD9,"Fitness Machine Control Point"}, - {0x2ACC,"Fitness Machine Feature"}, - {0x2ADA,"Fitness Machine Status"}, - {0x2A8B,"Five Zone Heart Rate Limits"}, - {0x2AB2,"Floor Number"}, - {0x2A8C,"Gender"}, - {0x2A51,"Glucose Feature"}, - {0x2A18,"Glucose Measurement"}, - {0x2A34,"Glucose Measurement Context"}, - {0x2A74,"Gust Factor"}, - {0x2A27,"Hardware Revision String"}, - {0x2A39,"Heart Rate Control Point"}, - {0x2A8D,"Heart Rate Max"}, - {0x2A37,"Heart Rate Measurement"}, - {0x2A7A,"Heat Index"}, - {0x2A8E,"Height"}, - {0x2A4C,"HID Control Point"}, - {0x2A4A,"HID Information"}, - {0x2A8F,"Hip Circumference"}, - {0x2ABA,"HTTP Control Point"}, - {0x2AB9,"HTTP Entity Body"}, - {0x2AB7,"HTTP Headers"}, - {0x2AB8,"HTTP Status Code"}, - {0x2ABB,"HTTPS Security"}, - {0x2A6F,"Humidity"}, - {0x2A2A,"IEEE 11073-20601 Regulatory Certification Data List"}, - {0x2AD2,"Indoor Bike Data"}, - {0x2AAD,"Indoor Positioning Configuration"}, - {0x2A36,"Intermediate Cuff Pressure"}, - {0x2A1E,"Intermediate Temperature"}, - {0x2A77,"Irradiance"}, - {0x2AA2,"Language"}, - {0x2A90,"Last Name"}, - {0x2AAE,"Latitude"}, - {0x2A6B,"LN Control Point"}, - {0x2A6A,"LN Feature"}, - {0x2AB1,"Local East Coordinate"}, - {0x2AB0,"Local North Coordinate"}, - {0x2A0F,"Local Time Information"}, - {0x2A67,"Location and Speed Characteristic"}, - {0x2AB5,"Location Name"}, - {0x2AAF,"Longitude"}, - {0x2A2C,"Magnetic Declination"}, - {0x2AA0,"Magnetic Flux Density - 2D"}, - {0x2AA1,"Magnetic Flux Density - 3D"}, - {0x2A29,"Manufacturer Name String"}, - {0x2A91,"Maximum Recommended Heart Rate"}, - {0x2A21,"Measurement Interval"}, - {0x2A24,"Model Number String"}, - {0x2A68,"Navigation"}, - {0x2A3E,"Network Availability"}, - {0x2A46,"New Alert"}, - {0x2AC5,"Object Action Control Point"}, - {0x2AC8,"Object Changed"}, - {0x2AC1,"Object First-Created"}, - {0x2AC3,"Object ID"}, - {0x2AC2,"Object Last-Modified"}, - {0x2AC6,"Object List Control Point"}, - {0x2AC7,"Object List Filter"}, - {0x2ABE,"Object Name"}, - {0x2AC4,"Object Properties"}, - {0x2AC0,"Object Size"}, - {0x2ABF,"Object Type"}, - {0x2ABD,"OTS Feature"}, - {0x2A04,"Peripheral Preferred Connection Parameters"}, - {0x2A02,"Peripheral Privacy Flag"}, - {0x2A5F,"PLX Continuous Measurement Characteristic"}, - {0x2A60,"PLX Features"}, - {0x2A5E,"PLX Spot-Check Measurement"}, - {0x2A50,"PnP ID"}, - {0x2A75,"Pollen Concentration"}, - {0x2A2F,"Position 2D"}, - {0x2A30,"Position 3D"}, - {0x2A69,"Position Quality"}, - {0x2A6D,"Pressure"}, - {0x2A4E,"Protocol Mode"}, - {0x2A62,"Pulse Oximetry Control Point"}, - {0x2A60,"Pulse Oximetry Pulsatile Event Characteristic"}, - {0x2A78,"Rainfall"}, - {0x2A03,"Reconnection Address"}, - {0x2A52,"Record Access Control Point"}, - {0x2A14,"Reference Time Information"}, - {0x2A3A,"Removable"}, - {0x2A4D,"Report"}, - {0x2A4B,"Report Map"}, - {0x2AC9,"Resolvable Private Address Only"}, - {0x2A92,"Resting Heart Rate"}, - {0x2A40,"Ringer Control point"}, - {0x2A41,"Ringer Setting"}, - {0x2AD1,"Rower Data"}, - {0x2A54,"RSC Feature"}, - {0x2A53,"RSC Measurement"}, - {0x2A55,"SC Control Point"}, - {0x2A4F,"Scan Interval Window"}, - {0x2A31,"Scan Refresh"}, - {0x2A3C,"Scientific Temperature Celsius"}, - {0x2A10,"Secondary Time Zone"}, - {0x2A5D,"Sensor Location"}, - {0x2A25,"Serial Number String"}, - {0x2A05,"Service Changed"}, - {0x2A3B,"Service Required"}, - {0x2A28,"Software Revision String"}, - {0x2A93,"Sport Type for Aerobic and Anaerobic Thresholds"}, - {0x2AD0,"Stair Climber Data"}, - {0x2ACF,"Step Climber Data"}, - {0x2A3D,"String"}, - {0x2AD7,"Supported Heart Rate Range"}, - {0x2AD5,"Supported Inclination Range"}, - {0x2A47,"Supported New Alert Category"}, - {0x2AD8,"Supported Power Range"}, - {0x2AD6,"Supported Resistance Level Range"}, - {0x2AD4,"Supported Speed Range"}, - {0x2A48,"Supported Unread Alert Category"}, - {0x2A23,"System ID"}, - {0x2ABC,"TDS Control Point"}, - {0x2A6E,"Temperature"}, - {0x2A1F,"Temperature Celsius"}, - {0x2A20,"Temperature Fahrenheit"}, - {0x2A1C,"Temperature Measurement"}, - {0x2A1D,"Temperature Type"}, - {0x2A94,"Three Zone Heart Rate Limits"}, - {0x2A12,"Time Accuracy"}, - {0x2A15,"Time Broadcast"}, - {0x2A13,"Time Source"}, - {0x2A16,"Time Update Control Point"}, - {0x2A17,"Time Update State"}, - {0x2A11,"Time with DST"}, - {0x2A0E,"Time Zone"}, - {0x2AD3,"Training Status"}, - {0x2ACD,"Treadmill Data"}, - {0x2A71,"True Wind Direction"}, - {0x2A70,"True Wind Speed"}, - {0x2A95,"Two Zone Heart Rate Limit"}, - {0x2A07,"Tx Power Level"}, - {0x2AB4,"Uncertainty"}, - {0x2A45,"Unread Alert Status"}, - {0x2AB6,"URI"}, - {0x2A9F,"User Control Point"}, - {0x2A9A,"User Index"}, - {0x2A76,"UV Index"}, - {0x2A96,"VO2 Max"}, - {0x2A97,"Waist Circumference"}, - {0x2A98,"Weight"}, - {0x2A9D,"Weight Measurement"}, - {0x2A9E,"Weight Scale Feature"}, - {0x2A79,"Wind Chill"}, - {0, ""} -}; - -/** - * @brief Mapping from service ids to names - */ -typedef struct { - const char* name; - const char* type; - uint32_t assignedNumber; -} gattService_t; - - -/** - * Definition of the service ids to names that we know about. - */ -static const gattService_t g_gattServices[] = { - {"Alert Notification Service", "org.bluetooth.service.alert_notification", 0x1811}, - {"Automation IO", "org.bluetooth.service.automation_io", 0x1815 }, - {"Battery Service","org.bluetooth.service.battery_service", 0x180F}, - {"Blood Pressure", "org.bluetooth.service.blood_pressure", 0x1810}, - {"Body Composition", "org.bluetooth.service.body_composition", 0x181B}, - {"Bond Management", "org.bluetooth.service.bond_management", 0x181E}, - {"Continuous Glucose Monitoring", "org.bluetooth.service.continuous_glucose_monitoring", 0x181F}, - {"Current Time Service", "org.bluetooth.service.current_time", 0x1805}, - {"Cycling Power", "org.bluetooth.service.cycling_power", 0x1818}, - {"Cycling Speed and Cadence", "org.bluetooth.service.cycling_speed_and_cadence", 0x1816}, - {"Device Information", "org.bluetooth.service.device_information", 0x180A}, - {"Environmental Sensing", "org.bluetooth.service.environmental_sensing", 0x181A}, - {"Generic Access", "org.bluetooth.service.generic_access", 0x1800}, - {"Generic Attribute", "org.bluetooth.service.generic_attribute", 0x1801}, - {"Glucose", "org.bluetooth.service.glucose", 0x1808}, - {"Health Thermometer", "org.bluetooth.service.health_thermometer", 0x1809}, - {"Heart Rate", "org.bluetooth.service.heart_rate", 0x180D}, - {"HTTP Proxy", "org.bluetooth.service.http_proxy", 0x1823}, - {"Human Interface Device", "org.bluetooth.service.human_interface_device", 0x1812}, - {"Immediate Alert", "org.bluetooth.service.immediate_alert", 0x1802}, - {"Indoor Positioning", "org.bluetooth.service.indoor_positioning", 0x1821}, - {"Internet Protocol Support", "org.bluetooth.service.internet_protocol_support", 0x1820}, - {"Link Loss", "org.bluetooth.service.link_loss", 0x1803}, - {"Location and Navigation", "org.bluetooth.service.location_and_navigation", 0x1819}, - {"Next DST Change Service", "org.bluetooth.service.next_dst_change", 0x1807}, - {"Object Transfer", "org.bluetooth.service.object_transfer", 0x1825}, - {"Phone Alert Status Service", "org.bluetooth.service.phone_alert_status", 0x180E}, - {"Pulse Oximeter", "org.bluetooth.service.pulse_oximeter", 0x1822}, - {"Reference Time Update Service", "org.bluetooth.service.reference_time_update", 0x1806}, - {"Running Speed and Cadence", "org.bluetooth.service.running_speed_and_cadence", 0x1814}, - {"Scan Parameters", "org.bluetooth.service.scan_parameters", 0x1813}, - {"Transport Discovery", "org.bluetooth.service.transport_discovery", 0x1824}, - {"Tx Power", "org.bluetooth.service.tx_power", 0x1804}, - {"User Data", "org.bluetooth.service.user_data", 0x181C}, - {"Weight Scale", "org.bluetooth.service.weight_scale", 0x181D}, - {"", "", 0 } -}; - - -/** - * @brief Convert characteristic properties into a string representation. - * @param [in] prop Characteristic properties. - * @return A string representation of characteristic properties. - */ -std::string BLEUtils::characteristicPropertiesToString(esp_gatt_char_prop_t prop) { - std::stringstream stream; - stream << - "broadcast: " << ((prop & ESP_GATT_CHAR_PROP_BIT_BROADCAST)?"1":"0") << - ", read: " << ((prop & ESP_GATT_CHAR_PROP_BIT_READ)?"1":"0") << - ", write_nr: " << ((prop & ESP_GATT_CHAR_PROP_BIT_WRITE_NR)?"1":"0") << - ", write: " << ((prop & ESP_GATT_CHAR_PROP_BIT_WRITE)?"1":"0") << - ", notify: " << ((prop & ESP_GATT_CHAR_PROP_BIT_NOTIFY)?"1":"0") << - ", indicate: " << ((prop & ESP_GATT_CHAR_PROP_BIT_INDICATE)?"1":"0") << - ", auth: " << ((prop & ESP_GATT_CHAR_PROP_BIT_AUTH)?"1":"0"); - return stream.str(); -} // characteristicPropertiesToString - -/** - * @brief Convert an esp_gatt_id_t to a string. - */ -static std::string gattIdToString(esp_gatt_id_t gattId) { - std::stringstream stream; - stream << "uuid: " << BLEUUID(gattId.uuid).toString() << ", inst_id: " << (int)gattId.inst_id; - //sprintf(buffer, "uuid: %s, inst_id: %d", uuidToString(gattId.uuid).c_str(), gattId.inst_id); - return stream.str(); -} // gattIdToString - - -/** - * @brief Convert an esp_ble_addr_type_t to a string representation. - */ -const char* BLEUtils::addressTypeToString(esp_ble_addr_type_t type) { - switch(type) { - case BLE_ADDR_TYPE_PUBLIC: - return "BLE_ADDR_TYPE_PUBLIC"; - case BLE_ADDR_TYPE_RANDOM: - return "BLE_ADDR_TYPE_RANDOM"; - case BLE_ADDR_TYPE_RPA_PUBLIC: - return "BLE_ADDR_TYPE_RPA_PUBLIC"; - case BLE_ADDR_TYPE_RPA_RANDOM: - return "BLE_ADDR_TYPE_RPA_RANDOM"; - default: - return " esp_ble_addr_type_t"; - } -} // addressTypeToString - - -/** - * @brief Convert the BLE Advertising Data flags to a string. - * @param adFlags The flags to convert - * @return std::string A string representation of the advertising flags. - */ -std::string BLEUtils::adFlagsToString(uint8_t adFlags) { - std::stringstream ss; - if (adFlags & (1<<0)) { - ss << "[LE Limited Discoverable Mode] "; - } - if (adFlags & (1<<1)) { - ss << "[LE General Discoverable Mode] "; - } - if (adFlags & (1<<2)) { - ss << "[BR/EDR Not Supported] "; - } - if (adFlags & (1<<3)) { - ss << "[Simultaneous LE and BR/EDR to Same Device Capable (Controller)] "; - } - if (adFlags & (1<<4)) { - ss << "[Simultaneous LE and BR/EDR to Same Device Capable (Host)] "; - } - return ss.str(); -} // adFlagsToString - - -/** - * @brief Given an advertising type, return a string representation of the type. - * - * For details see ... - * https://www.bluetooth.com/specifications/assigned-numbers/generic-access-profile - * - * @return A string representation of the type. - */ -const char* BLEUtils::advTypeToString(uint8_t advType) { - switch(advType) { - case ESP_BLE_AD_TYPE_FLAG: // 0x01 - return "ESP_BLE_AD_TYPE_FLAG"; - - case ESP_BLE_AD_TYPE_16SRV_PART: // 0x02 - return "ESP_BLE_AD_TYPE_16SRV_PART"; - - case ESP_BLE_AD_TYPE_16SRV_CMPL: // 0x03 - return "ESP_BLE_AD_TYPE_16SRV_CMPL"; - - case ESP_BLE_AD_TYPE_32SRV_PART: // 0x04 - return "ESP_BLE_AD_TYPE_32SRV_PART"; - - case ESP_BLE_AD_TYPE_32SRV_CMPL: // 0x05 - return "ESP_BLE_AD_TYPE_32SRV_CMPL"; - - case ESP_BLE_AD_TYPE_128SRV_PART: // 0x06 - return "ESP_BLE_AD_TYPE_128SRV_PART"; - - case ESP_BLE_AD_TYPE_128SRV_CMPL: // 0x07 - return "ESP_BLE_AD_TYPE_128SRV_CMPL"; - - case ESP_BLE_AD_TYPE_NAME_SHORT: // 0x08 - return "ESP_BLE_AD_TYPE_NAME_SHORT"; - - case ESP_BLE_AD_TYPE_NAME_CMPL: // 0x09 - return "ESP_BLE_AD_TYPE_NAME_CMPL"; - - case ESP_BLE_AD_TYPE_TX_PWR: // 0x0a - return "ESP_BLE_AD_TYPE_TX_PWR"; - - case ESP_BLE_AD_TYPE_DEV_CLASS: // 0x0b - return "ESP_BLE_AD_TYPE_DEV_CLASS"; - - case ESP_BLE_AD_TYPE_SM_TK: // 0x10 - return "ESP_BLE_AD_TYPE_SM_TK"; - - case ESP_BLE_AD_TYPE_SM_OOB_FLAG: // 0x11 - return "ESP_BLE_AD_TYPE_SM_OOB_FLAG"; - - case ESP_BLE_AD_TYPE_INT_RANGE: // 0x12 - return "ESP_BLE_AD_TYPE_INT_RANGE"; - - case ESP_BLE_AD_TYPE_SOL_SRV_UUID: // 0x14 - return "ESP_BLE_AD_TYPE_SOL_SRV_UUID"; - - case ESP_BLE_AD_TYPE_128SOL_SRV_UUID: // 0x15 - return "ESP_BLE_AD_TYPE_128SOL_SRV_UUID"; - - case ESP_BLE_AD_TYPE_SERVICE_DATA: // 0x16 - return "ESP_BLE_AD_TYPE_SERVICE_DATA"; - - case ESP_BLE_AD_TYPE_PUBLIC_TARGET: // 0x17 - return "ESP_BLE_AD_TYPE_PUBLIC_TARGET"; - - case ESP_BLE_AD_TYPE_RANDOM_TARGET: // 0x18 - return "ESP_BLE_AD_TYPE_RANDOM_TARGET"; - - case ESP_BLE_AD_TYPE_APPEARANCE: // 0x19 - return "ESP_BLE_AD_TYPE_APPEARANCE"; - - case ESP_BLE_AD_TYPE_ADV_INT: // 0x1a - return "ESP_BLE_AD_TYPE_ADV_INT"; - - case ESP_BLE_AD_TYPE_32SOL_SRV_UUID: - return "ESP_BLE_AD_TYPE_32SOL_SRV_UUID"; - - case ESP_BLE_AD_TYPE_32SERVICE_DATA: // 0x20 - return "ESP_BLE_AD_TYPE_32SERVICE_DATA"; - - case ESP_BLE_AD_TYPE_128SERVICE_DATA: // 0x21 - return "ESP_BLE_AD_TYPE_128SERVICE_DATA"; - - case ESP_BLE_AD_MANUFACTURER_SPECIFIC_TYPE: // 0xff - return "ESP_BLE_AD_MANUFACTURER_SPECIFIC_TYPE"; - - default: - ESP_LOGD(LOG_TAG, " adv data type: 0x%x", advType); - return ""; - } // End switch -} // advTypeToString - - -esp_gatt_id_t BLEUtils::buildGattId(esp_bt_uuid_t uuid, uint8_t inst_id) { - esp_gatt_id_t retGattId; - retGattId.uuid = uuid; - retGattId.inst_id = inst_id; - return retGattId; -} - -esp_gatt_srvc_id_t BLEUtils::buildGattSrvcId(esp_gatt_id_t gattId, - bool is_primary) { - esp_gatt_srvc_id_t retSrvcId; - retSrvcId.id = gattId; - retSrvcId.is_primary = is_primary; - return retSrvcId; -} - -/** - * @brief Create a hex representation of data. - * - * @param [in] target Where to write the hex string. If this is null, we malloc storage. - * @param [in] source The start of the binary data. - * @param [in] length The length of the data to convert. - * @return A pointer to the formatted buffer. - */ -char* BLEUtils::buildHexData(uint8_t *target, uint8_t *source, uint8_t length) { -// Guard against too much data. - if (length > 100) { - length = 100; - } - - if (target == nullptr) { - target = (uint8_t *)malloc(length * 2 + 1); - if (target == nullptr) { - ESP_LOGE(LOG_TAG, "buildHexData: malloc failed"); - return nullptr; - } - } - char *startOfData = (char *)target; - - int i; - for (i=0; iadv_data_cmpl.status); - break; - } // ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT - - - // - // ESP_GAP_BLE_ADV_DATA_RAW_SET_COMPLETE_EVT - // - // adv_data_raw_cmpl - // - esp_bt_status_t status - // - case ESP_GAP_BLE_ADV_DATA_RAW_SET_COMPLETE_EVT: { - ESP_LOGD(LOG_TAG, "[status: %d]", param->adv_data_raw_cmpl.status); - break; - } // ESP_GAP_BLE_ADV_DATA_RAW_SET_COMPLETE_EVT - - - // - // ESP_GAP_BLE_ADV_START_COMPLETE_EVT - // - // adv_start_cmpl - // - esp_bt_status_t status - // - case ESP_GAP_BLE_ADV_START_COMPLETE_EVT: { - ESP_LOGD(LOG_TAG, "[status: %d]", param->adv_start_cmpl.status); - break; - } // ESP_GAP_BLE_ADV_START_COMPLETE_EVT - - - // - // ESP_GAP_BLE_ADV_STOP_COMPLETE_EVT - // - // adv_stop_cmpl - // - esp_bt_status_t status - // - case ESP_GAP_BLE_ADV_STOP_COMPLETE_EVT: { - ESP_LOGD(LOG_TAG, "[status: %d]", param->adv_stop_cmpl.status); - break; - } // ESP_GAP_BLE_ADV_STOP_COMPLETE_EVT - - - // - // ESP_GAP_BLE_AUTH_CMPL_EVT - // - // auth_cmpl - // - esp_bd_addr_t bd_addr - // - bool key_present - // - esp_link_key key - // - bool success - // - uint8_t fail_reason - // - esp_bd_addr_type_t addr_type - // - esp_bt_dev_type_t dev_type - // - case ESP_GAP_BLE_AUTH_CMPL_EVT: { - ESP_LOGD(LOG_TAG, "[bd_addr: %s, key_present: %d, key: ***, key_type: %d, success: %d, fail_reason: %d, addr_type: ***, dev_type: %s]", - BLEAddress(param->ble_security.auth_cmpl.bd_addr).toString().c_str(), - param->ble_security.auth_cmpl.key_present, - param->ble_security.auth_cmpl.key_type, - param->ble_security.auth_cmpl.success, - param->ble_security.auth_cmpl.fail_reason, - BLEUtils::devTypeToString(param->ble_security.auth_cmpl.dev_type) - ); - break; - } // ESP_GAP_BLE_AUTH_CMPL_EVT - - - // - // ESP_GAP_BLE_CLEAR_BOND_DEV_COMPLETE_EVT - // - // clear_bond_dev_cmpl - // - esp_bt_status_t status - // - case ESP_GAP_BLE_CLEAR_BOND_DEV_COMPLETE_EVT: { - ESP_LOGD(LOG_TAG, "[status: %d]", param->clear_bond_dev_cmpl.status); - break; - } // ESP_GAP_BLE_CLEAR_BOND_DEV_COMPLETE_EVT - - - // - // ESP_GAP_BLE_LOCAL_IR_EVT - // - case ESP_GAP_BLE_LOCAL_IR_EVT: { - break; - } // ESP_GAP_BLE_LOCAL_IR_EVT - - - // - // ESP_GAP_BLE_LOCAL_ER_EVT - // - case ESP_GAP_BLE_LOCAL_ER_EVT: { - break; - } // ESP_GAP_BLE_LOCAL_ER_EVT - - - // - // ESP_GAP_BLE_NC_REQ_EVT - // - case ESP_GAP_BLE_NC_REQ_EVT: { - ESP_LOGD(LOG_TAG, "[bd_addr: %s, passkey: %d]", - BLEAddress(param->ble_security.key_notif.bd_addr).toString().c_str(), - param->ble_security.key_notif.passkey); - break; - } // ESP_GAP_BLE_NC_REQ_EVT - - - // - // ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT - // - // read_rssi_cmpl - // - esp_bt_status_t status - // - int8_t rssi - // - esp_bd_addr_t remote_addr - // - case ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT: { - ESP_LOGD(LOG_TAG, "[status: %d, rssi: %d, remote_addr: %s]", - param->read_rssi_cmpl.status, - param->read_rssi_cmpl.rssi, - BLEAddress(param->read_rssi_cmpl.remote_addr).toString().c_str() - ); - break; - } // ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT - - - // - // ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT - // - // scan_param_cmpl. - // - esp_bt_status_t status - // - case ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT: { - ESP_LOGD(LOG_TAG, "[status: %d]", param->scan_param_cmpl.status); - break; - } // ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT - - - // - // ESP_GAP_BLE_SCAN_RESULT_EVT - // - // scan_rst: - // - search_evt - // - bda - // - dev_type - // - ble_addr_type - // - ble_evt_type - // - rssi - // - ble_adv - // - flag - // - num_resps - // - adv_data_len - // - scan_rsp_len - // - case ESP_GAP_BLE_SCAN_RESULT_EVT: { - switch(param->scan_rst.search_evt) { - case ESP_GAP_SEARCH_INQ_RES_EVT: { - ESP_LOGD(LOG_TAG, "search_evt: %s, bda: %s, dev_type: %s, ble_addr_type: %s, ble_evt_type: %s, rssi: %d, ble_adv: ??, flag: %d (%s), num_resps: %d, adv_data_len: %d, scan_rsp_len: %d", - searchEventTypeToString(param->scan_rst.search_evt), - BLEAddress(param->scan_rst.bda).toString().c_str(), - devTypeToString(param->scan_rst.dev_type), - addressTypeToString(param->scan_rst.ble_addr_type), - eventTypeToString(param->scan_rst.ble_evt_type), - param->scan_rst.rssi, - param->scan_rst.flag, - adFlagsToString(param->scan_rst.flag).c_str(), - param->scan_rst.num_resps, - param->scan_rst.adv_data_len, - param->scan_rst.scan_rsp_len - ); - break; - } // ESP_GAP_SEARCH_INQ_RES_EVT - - default: { - ESP_LOGD(LOG_TAG, "search_evt: %s",searchEventTypeToString(param->scan_rst.search_evt)); - break; - } - } - break; - } // ESP_GAP_BLE_SCAN_RESULT_EVT - - - // - // ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT - // - // scan_rsp_data_cmpl - // - esp_bt_status_t status - // - case ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT: { - ESP_LOGD(LOG_TAG, "[status: %d]", param->scan_rsp_data_cmpl.status); - break; - } // ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT - - - // - // ESP_GAP_BLE_SCAN_RSP_DATA_RAW_SET_COMPLETE_EVT - // - case ESP_GAP_BLE_SCAN_RSP_DATA_RAW_SET_COMPLETE_EVT: { - ESP_LOGD(LOG_TAG, "[status: %d]", param->scan_rsp_data_raw_cmpl.status); - break; - } // ESP_GAP_BLE_SCAN_RSP_DATA_RAW_SET_COMPLETE_EVT - - - // - // ESP_GAP_BLE_SCAN_START_COMPLETE_EVT - // - // scan_start_cmpl - // - esp_bt_status_t status - case ESP_GAP_BLE_SCAN_START_COMPLETE_EVT: { - ESP_LOGD(LOG_TAG, "[status: %d]", param->scan_start_cmpl.status); - break; - } // ESP_GAP_BLE_SCAN_START_COMPLETE_EVT - - - // - // ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT - // - // scan_stop_cmpl - // - esp_bt_status_t status - // - case ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT: { - ESP_LOGD(LOG_TAG, "[status: %d]", param->scan_stop_cmpl.status); - break; - } // ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT - - - // - // ESP_GAP_BLE_UPDATE_CONN_PARAMS_EVT - // - // update_conn_params - // - esp_bt_status_t status - // - esp_bd_addr_t bda - // - uint16_t min_int - // - uint16_t max_int - // - uint16_t latency - // - uint16_t conn_int - // - uint16_t timeout - // - case ESP_GAP_BLE_UPDATE_CONN_PARAMS_EVT: { - ESP_LOGD(LOG_TAG, "[status: %d, bd_addr: %s, min_int: %d, max_int: %d, latency: %d, conn_int: %d, timeout: %d]", - param->update_conn_params.status, - BLEAddress(param->update_conn_params.bda).toString().c_str(), - param->update_conn_params.min_int, - param->update_conn_params.max_int, - param->update_conn_params.latency, - param->update_conn_params.conn_int, - param->update_conn_params.timeout - ); - break; - } // ESP_GAP_BLE_SCAN_UPDATE_CONN_PARAMS_EVT - - - // - // ESP_GAP_BLE_SEC_REQ_EVT - // - case ESP_GAP_BLE_SEC_REQ_EVT: { - ESP_LOGD(LOG_TAG, "[bd_addr: %s]", BLEAddress(param->ble_security.ble_req.bd_addr).toString().c_str()); - break; - } // ESP_GAP_BLE_SEC_REQ_EVT - - - default: { - ESP_LOGD(LOG_TAG, "*** dumpGapEvent: Logger not coded ***"); - break; - } // default - } // switch -} // dumpGapEvent - - -/** - * @brief Decode and dump a GATT client event - * - * @param [in] event The type of event received. - * @param [in] evtParam The data associated with the event. - */ -void BLEUtils::dumpGattClientEvent( - esp_gattc_cb_event_t event, - esp_gatt_if_t gattc_if, - esp_ble_gattc_cb_param_t* evtParam) { - - //esp_ble_gattc_cb_param_t *evtParam = (esp_ble_gattc_cb_param_t *)param; - ESP_LOGD(LOG_TAG, "GATT Event: %s", BLEUtils::gattClientEventTypeToString(event).c_str()); - switch(event) { - // - // ESP_GATTC_CLOSE_EVT - // - // close: - // - esp_gatt_status_t status - // - uint16_t conn_id - // - esp_bd_addr_t remote_bda - // - esp_gatt_conn_reason_t reason - // - case ESP_GATTC_CLOSE_EVT: { - ESP_LOGD(LOG_TAG, "[status: %s, reason:%s, conn_id: %d]", - BLEUtils::gattStatusToString(evtParam->close.status).c_str(), - BLEUtils::gattCloseReasonToString(evtParam->close.reason).c_str(), - evtParam->close.conn_id); - break; - } - - // - // ESP_GATTC_CONNECT_EVT - // - // connect: - // - esp_gatt_status_t status - // - uint16_t conn_id - // - esp_bd_addr_t remote_bda - case ESP_GATTC_CONNECT_EVT: { - ESP_LOGD(LOG_TAG, "[conn_id: %d, remote_bda: %s]", - evtParam->connect.conn_id, - BLEAddress(evtParam->connect.remote_bda).toString().c_str() - ); - break; - } - - // - // ESP_GATTC_DISCONNECT_EVT - // - // disconnect: - // - esp_gatt_conn_reason_t reason - // - uint16_t conn_id - // - esp_bd_addr_t remote_bda - case ESP_GATTC_DISCONNECT_EVT: { - ESP_LOGD(LOG_TAG, "[reason: %s, conn_id: %d, remote_bda: %s]", - BLEUtils::gattCloseReasonToString(evtParam->disconnect.reason).c_str(), - evtParam->disconnect.conn_id, - BLEAddress(evtParam->disconnect.remote_bda).toString().c_str() - ); - break; - } // ESP_GATTC_DISCONNECT_EVT - - // - // ESP_GATTC_GET_CHAR_EVT - // - // get_char: - // - esp_gatt_status_t status - // - uin1t6_t conn_id - // - esp_gatt_srvc_id_t srvc_id - // - esp_gatt_id_t char_id - // - esp_gatt_char_prop_t char_prop - // - /* - case ESP_GATTC_GET_CHAR_EVT: { - - // If the status of the event shows that we have a value other than ESP_GATT_OK then the - // characteristic fields are not set to a usable value .. so don't try and log them. - if (evtParam->get_char.status == ESP_GATT_OK) { - std::string description = "Unknown"; - if (evtParam->get_char.char_id.uuid.len == ESP_UUID_LEN_16) { - description = BLEUtils::gattCharacteristicUUIDToString(evtParam->get_char.char_id.uuid.uuid.uuid16); - } - ESP_LOGD(LOG_TAG, "[status: %s, conn_id: %d, srvc_id: %s, char_id: %s [description: %s]\nchar_prop: %s]", - BLEUtils::gattStatusToString(evtParam->get_char.status).c_str(), - evtParam->get_char.conn_id, - BLEUtils::gattServiceIdToString(evtParam->get_char.srvc_id).c_str(), - gattIdToString(evtParam->get_char.char_id).c_str(), - description.c_str(), - BLEUtils::characteristicPropertiesToString(evtParam->get_char.char_prop).c_str() - ); - } else { - ESP_LOGD(LOG_TAG, "[status: %s, conn_id: %d, srvc_id: %s]", - BLEUtils::gattStatusToString(evtParam->get_char.status).c_str(), - evtParam->get_char.conn_id, - BLEUtils::gattServiceIdToString(evtParam->get_char.srvc_id).c_str() - ); - } - break; - } // ESP_GATTC_GET_CHAR_EVT - */ - - // - // ESP_GATTC_NOTIFY_EVT - // - // notify - // uint16_t conn_id - // esp_bd_addr_t remote_bda - // handle handle - // uint16_t value_len - // uint8_t* value - // bool is_notify - // - case ESP_GATTC_NOTIFY_EVT: { - ESP_LOGD(LOG_TAG, "[conn_id: %d, remote_bda: %s, handle: %d 0x%.2x, value_len: %d, is_notify: %d]", - evtParam->notify.conn_id, - BLEAddress(evtParam->notify.remote_bda).toString().c_str(), - evtParam->notify.handle, - evtParam->notify.handle, - evtParam->notify.value_len, - evtParam->notify.is_notify - ); - break; - } - - // - // ESP_GATTC_OPEN_EVT - // - // open: - // - esp_gatt_status_t status - // - uint16_t conn_id - // - esp_bd_addr_t remote_bda - // - uint16_t mtu - // - case ESP_GATTC_OPEN_EVT: { - ESP_LOGD(LOG_TAG, "[status: %s, conn_id: %d, remote_bda: %s, mtu: %d]", - BLEUtils::gattStatusToString(evtParam->open.status).c_str(), - evtParam->open.conn_id, - BLEAddress(evtParam->open.remote_bda).toString().c_str(), - evtParam->open.mtu); - break; - } // ESP_GATTC_OPEN_EVT - - - // - // ESP_GATTC_READ_CHAR_EVT - // - // Callback to indicate that requested data that we wanted to read is now available. - // - // read: - // esp_gatt_status_t status - // uint16_t conn_id - // uint16_t handle - // uint8_t* value - // uint16_t value_type - // uint16_t value_len - case ESP_GATTC_READ_CHAR_EVT: { - ESP_LOGD(LOG_TAG, "[status: %s, conn_id: %d, handle: %d 0x%.2x, value_len: %d]", - BLEUtils::gattStatusToString(evtParam->read.status).c_str(), - evtParam->read.conn_id, - evtParam->read.handle, - evtParam->read.handle, - evtParam->read.value_len - ); - if (evtParam->read.status == ESP_GATT_OK) { - GeneralUtils::hexDump(evtParam->read.value, evtParam->read.value_len); - /* - char *pHexData = BLEUtils::buildHexData(nullptr, evtParam->read.value, evtParam->read.value_len); - ESP_LOGD(LOG_TAG, "value: %s \"%s\"", pHexData, BLEUtils::buildPrintData(evtParam->read.value, evtParam->read.value_len).c_str()); - free(pHexData); - */ - } - break; - } // ESP_GATTC_READ_CHAR_EVT - - - // - // ESP_GATTC_REG_EVT - // - // reg: - // - esp_gatt_status_t status - // - uint16_t app_id - // - case ESP_GATTC_REG_EVT: { - ESP_LOGD(LOG_TAG, "[status: %s, app_id: 0x%x]", - BLEUtils::gattStatusToString(evtParam->reg.status).c_str(), - evtParam->reg.app_id); - break; - } // ESP_GATTC_REG_EVT - - - // - // ESP_GATTC_REG_FOR_NOTIFY_EVT - // - // reg_for_notify: - // - esp_gatt_status_t status - // - uint16_t handle - case ESP_GATTC_REG_FOR_NOTIFY_EVT: { - ESP_LOGD(LOG_TAG, "[status: %s, handle: %d 0x%.2x]", - BLEUtils::gattStatusToString(evtParam->reg_for_notify.status).c_str(), - evtParam->reg_for_notify.handle, - evtParam->reg_for_notify.handle - ); - break; - } // ESP_GATTC_REG_FOR_NOTIFY_EVT - - - // - // ESP_GATTC_SEARCH_CMPL_EVT - // - // search_cmpl: - // - esp_gatt_status_t status - // - uint16_t conn_id - // - case ESP_GATTC_SEARCH_CMPL_EVT: { - ESP_LOGD(LOG_TAG, "[status: %s, conn_id: %d]", - BLEUtils::gattStatusToString(evtParam->search_cmpl.status).c_str(), - evtParam->search_cmpl.conn_id); - break; - } // ESP_GATTC_SEARCH_CMPL_EVT - - - // - // ESP_GATTC_SEARCH_RES_EVT - // - // search_res: - // - uint16_t conn_id - // - uint16_t start_handle - // - uint16_t end_handle - // - esp_gatt_id_t srvc_id - // - case ESP_GATTC_SEARCH_RES_EVT: { - ESP_LOGD(LOG_TAG, "[conn_id: %d, start_handle: %d 0x%.2x, end_handle: %d 0x%.2x, srvc_id: %s", - evtParam->search_res.conn_id, - evtParam->search_res.start_handle, - evtParam->search_res.start_handle, - evtParam->search_res.end_handle, - evtParam->search_res.end_handle, - gattIdToString(evtParam->search_res.srvc_id).c_str()); - break; - } // ESP_GATTC_SEARCH_RES_EVT - - - // - // ESP_GATTC_WRITE_CHAR_EVT - // - // write: - // - esp_gatt_status_t status - // - uint16_t conn_id - // - uint16_t handle - // - uint16_t offset - // - case ESP_GATTC_WRITE_CHAR_EVT: { - ESP_LOGD(LOG_TAG, "[status: %s, conn_id: %d, handle: %d 0x%.2x, offset: %d]", - BLEUtils::gattStatusToString(evtParam->write.status).c_str(), - evtParam->write.conn_id, - evtParam->write.handle, - evtParam->write.handle, - evtParam->write.offset - ); - break; - } // ESP_GATTC_WRITE_CHAR_EVT - - default: - break; - } -} // dumpGattClientEvent - - -/** - * @brief Dump the details of a GATT server event. - * A GATT Server event is a callback received from the BLE subsystem when we are acting as a BLE - * server. The callback indicates the type of event in the `event` field. The `evtParam` is a - * union of structures where we can use the `event` to indicate which of the structures has been - * populated and hence is valid. - * - * @param [in] event The event type that was posted. - * @param [in] evtParam A union of structures only one of which is populated. - */ -void BLEUtils::dumpGattServerEvent( - esp_gatts_cb_event_t event, - esp_gatt_if_t gatts_if, - esp_ble_gatts_cb_param_t* evtParam) { - ESP_LOGD(LOG_TAG, "GATT ServerEvent: %s", BLEUtils::gattServerEventTypeToString(event).c_str()); - switch(event) { - - case ESP_GATTS_ADD_CHAR_DESCR_EVT: { - ESP_LOGD(LOG_TAG, "[status: %s, attr_handle: %d 0x%.2x, service_handle: %d 0x%.2x, char_uuid: %s]", - gattStatusToString(evtParam->add_char_descr.status).c_str(), - evtParam->add_char_descr.attr_handle, - evtParam->add_char_descr.attr_handle, - evtParam->add_char_descr.service_handle, - evtParam->add_char_descr.service_handle, - BLEUUID(evtParam->add_char_descr.descr_uuid).toString().c_str()); - break; - } // ESP_GATTS_ADD_CHAR_DESCR_EVT - - case ESP_GATTS_ADD_CHAR_EVT: { - if (evtParam->add_char.status == ESP_GATT_OK) { - ESP_LOGD(LOG_TAG, "[status: %s, attr_handle: %d 0x%.2x, service_handle: %d 0x%.2x, char_uuid: %s]", - gattStatusToString(evtParam->add_char.status).c_str(), - evtParam->add_char.attr_handle, - evtParam->add_char.attr_handle, - evtParam->add_char.service_handle, - evtParam->add_char.service_handle, - BLEUUID(evtParam->add_char.char_uuid).toString().c_str()); - } else { - ESP_LOGE(LOG_TAG, "[status: %s, attr_handle: %d 0x%.2x, service_handle: %d 0x%.2x, char_uuid: %s]", - gattStatusToString(evtParam->add_char.status).c_str(), - evtParam->add_char.attr_handle, - evtParam->add_char.attr_handle, - evtParam->add_char.service_handle, - evtParam->add_char.service_handle, - BLEUUID(evtParam->add_char.char_uuid).toString().c_str()); - } - break; - } // ESP_GATTS_ADD_CHAR_EVT - - - // ESP_GATTS_CONF_EVT - // - // conf: - // - esp_gatt_status_t status – The status code. - // - uint16_t conn_id – The connection used. - // - case ESP_GATTS_CONF_EVT: { - ESP_LOGD(LOG_TAG, "[status: %s, conn_id: 0x%.2x]", - gattStatusToString(evtParam->conf.status).c_str(), - evtParam->conf.conn_id); - break; - } // ESP_GATTS_CONF_EVT - - - case ESP_GATTS_CONGEST_EVT: { - ESP_LOGD(LOG_TAG, "[conn_id: %d, congested: %d]", - evtParam->congest.conn_id, - evtParam->congest.congested); - break; - } // ESP_GATTS_CONGEST_EVT - - case ESP_GATTS_CONNECT_EVT: { - ESP_LOGD(LOG_TAG, "[conn_id: %d, remote_bda: %s]", - evtParam->connect.conn_id, - BLEAddress(evtParam->connect.remote_bda).toString().c_str()); - break; - } // ESP_GATTS_CONNECT_EVT - - case ESP_GATTS_CREATE_EVT: { - ESP_LOGD(LOG_TAG, "[status: %s, service_handle: %d 0x%.2x, service_id: [%s]]", - gattStatusToString(evtParam->create.status).c_str(), - evtParam->create.service_handle, - evtParam->create.service_handle, - gattServiceIdToString(evtParam->create.service_id).c_str()); - break; - } // ESP_GATTS_CREATE_EVT - - case ESP_GATTS_DISCONNECT_EVT: { - ESP_LOGD(LOG_TAG, "[conn_id: %d, remote_bda: %s]", - evtParam->connect.conn_id, - BLEAddress(evtParam->connect.remote_bda).toString().c_str()); - break; - } // ESP_GATTS_DISCONNECT_EVT - - - // ESP_GATTS_EXEC_WRITE_EVT - // exec_write: - // - uint16_t conn_id - // - uint32_t trans_id - // - esp_bd_addr_t bda - // - uint8_t exec_write_flag - // - case ESP_GATTS_EXEC_WRITE_EVT: { - char* pWriteFlagText; - switch(evtParam->exec_write.exec_write_flag) { - case ESP_GATT_PREP_WRITE_EXEC: { - pWriteFlagText = (char*)"WRITE"; - break; - } - - case ESP_GATT_PREP_WRITE_CANCEL: { - pWriteFlagText = (char*)"CANCEL"; - break; - } - - default: - pWriteFlagText = (char*)""; - break; - } - - ESP_LOGD(LOG_TAG, "[conn_id: %d, trans_id: %d, bda: %s, exec_write_flag: 0x%.2x=%s]", - evtParam->exec_write.conn_id, - evtParam->exec_write.trans_id, - BLEAddress(evtParam->exec_write.bda).toString().c_str(), - evtParam->exec_write.exec_write_flag, - pWriteFlagText); - break; - } // ESP_GATTS_DISCONNECT_EVT - - - case ESP_GATTS_MTU_EVT: { - ESP_LOGD(LOG_TAG, "[conn_id: %d, mtu: %d]", - evtParam->mtu.conn_id, - evtParam->mtu.mtu); - break; - } // ESP_GATTS_MTU_EVT - - case ESP_GATTS_READ_EVT: { - ESP_LOGD(LOG_TAG, "[conn_id: %d, trans_id: %d, bda: %s, handle: 0x%.2x, is_long: %d, need_rsp:%d]", - evtParam->read.conn_id, - evtParam->read.trans_id, - BLEAddress(evtParam->read.bda).toString().c_str(), - evtParam->read.handle, - evtParam->read.is_long, - evtParam->read.need_rsp); - break; - } // ESP_GATTS_READ_EVT - - case ESP_GATTS_RESPONSE_EVT: { - ESP_LOGD(LOG_TAG, "[status: %s, handle: 0x%.2x]", - gattStatusToString(evtParam->rsp.status).c_str(), - evtParam->rsp.handle); - break; - } // ESP_GATTS_RESPONSE_EVT - - case ESP_GATTS_REG_EVT: { - ESP_LOGD(LOG_TAG, "[status: %s, app_id: %d]", - gattStatusToString(evtParam->reg.status).c_str(), - evtParam->reg.app_id); - break; - } // ESP_GATTS_REG_EVT - - - // ESP_GATTS_START_EVT - // - // start: - // - esp_gatt_status_t status - // - uint16_t service_handle - // - case ESP_GATTS_START_EVT: { - ESP_LOGD(LOG_TAG, "[status: %s, service_handle: 0x%.2x]", - gattStatusToString(evtParam->start.status).c_str(), - evtParam->start.service_handle); - break; - } // ESP_GATTS_START_EVT - - - // ESP_GATTS_WRITE_EVT - // - // write: - // - uint16_t conn_id – The connection id. - // - uint16_t trans_id – The transfer id. - // - esp_bd_addr_t bda – The address of the partner. - // - uint16_t handle – The attribute handle. - // - uint16_t offset – The offset of the currently received within the whole value. - // - bool need_rsp – Do we need a response? - // - bool is_prep – Is this a write prepare? If set, then this is to be considered part of the received value and not the whole value. A subsequent ESP_GATTS_EXEC_WRITE will mark the total. - // - uint16_t len – The length of the incoming value part. - // - uint8_t* value – The data for this value part. - // - case ESP_GATTS_WRITE_EVT: { - ESP_LOGD(LOG_TAG, "[conn_id: %d, trans_id: %d, bda: %s, handle: 0x%.2x, offset: %d, need_rsp: %d, is_prep: %d, len: %d]", - evtParam->write.conn_id, - evtParam->write.trans_id, - BLEAddress(evtParam->write.bda).toString().c_str(), - evtParam->write.handle, - evtParam->write.offset, - evtParam->write.need_rsp, - evtParam->write.is_prep, - evtParam->write.len); - char* pHex = buildHexData(nullptr, evtParam->write.value, evtParam->write.len); - ESP_LOGD(LOG_TAG, "[Data: %s]", pHex); - free(pHex); - break; - } // ESP_GATTS_WRITE_EVT - - default: - ESP_LOGD(LOG_TAG, "dumpGattServerEvent: *** NOT CODED ***"); - break; - } -} // dumpGattServerEvent - - -/** - * @brief Convert a BLE event type to a string. - * @param [in] eventType The event type. - * @return The event type as a string. - */ -const char* BLEUtils::eventTypeToString(esp_ble_evt_type_t eventType) { - switch(eventType) { - case ESP_BLE_EVT_CONN_ADV: - return "ESP_BLE_EVT_CONN_ADV"; - case ESP_BLE_EVT_CONN_DIR_ADV: - return "ESP_BLE_EVT_CONN_DIR_ADV"; - case ESP_BLE_EVT_DISC_ADV: - return "ESP_BLE_EVT_DISC_ADV"; - case ESP_BLE_EVT_NON_CONN_ADV: - return "ESP_BLE_EVT_NON_CONN_ADV"; - case ESP_BLE_EVT_SCAN_RSP: - return "ESP_BLE_EVT_SCAN_RSP"; - default: - ESP_LOGD(LOG_TAG, "Unknown esp_ble_evt_type_t: %d (0x%.2x)", eventType, eventType); - return "*** Unknown ***"; - } -} // eventTypeToString - - - -/** - * @brief Convert a BT GAP event type to a string representation. - * @param [in] eventType The type of event. - * @return A string representation of the event type. - */ -const char* BLEUtils::gapEventToString(uint32_t eventType) { - switch(eventType) { - case ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT: - return "ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT"; - - case ESP_GAP_BLE_ADV_DATA_RAW_SET_COMPLETE_EVT: - return "ESP_GAP_BLE_ADV_DATA_RAW_SET_COMPLETE_EVT"; - - case ESP_GAP_BLE_ADV_START_COMPLETE_EVT: - return "ESP_GAP_BLE_ADV_START_COMPLETE_EVT"; - - case ESP_GAP_BLE_ADV_STOP_COMPLETE_EVT: /*!< When stop adv complete, the event comes */ - return "ESP_GAP_BLE_ADV_STOP_COMPLETE_EVT"; - - case ESP_GAP_BLE_AUTH_CMPL_EVT: /* Authentication complete indication. */ - return "ESP_GAP_BLE_AUTH_CMPL_EVT"; - - case ESP_GAP_BLE_CLEAR_BOND_DEV_COMPLETE_EVT: - return "ESP_GAP_BLE_CLEAR_BOND_DEV_COMPLETE_EVT"; - - case ESP_GAP_BLE_GET_BOND_DEV_COMPLETE_EVT: - return "ESP_GAP_BLE_GET_BOND_DEV_COMPLETE_EVT"; - - case ESP_GAP_BLE_KEY_EVT: /* BLE key event for peer device keys */ - return "ESP_GAP_BLE_KEY_EVT"; - - case ESP_GAP_BLE_LOCAL_IR_EVT: /* BLE local IR event */ - return "ESP_GAP_BLE_LOCAL_IR_EVT"; - - case ESP_GAP_BLE_LOCAL_ER_EVT: /* BLE local ER event */ - return "ESP_GAP_BLE_LOCAL_ER_EVT"; - - case ESP_GAP_BLE_NC_REQ_EVT: /* Numeric Comparison request event */ - return "ESP_GAP_BLE_NC_REQ_EVT"; - - case ESP_GAP_BLE_OOB_REQ_EVT: /* OOB request event */ - return "ESP_GAP_BLE_OOB_REQ_EVT"; - - case ESP_GAP_BLE_PASSKEY_NOTIF_EVT: /* passkey notification event */ - return "ESP_GAP_BLE_PASSKEY_NOTIF_EVT"; - - case ESP_GAP_BLE_PASSKEY_REQ_EVT: /* passkey request event */ - return "ESP_GAP_BLE_PASSKEY_REQ_EVT"; - - case ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT: - return "ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT"; - - case ESP_GAP_BLE_REMOVE_BOND_DEV_COMPLETE_EVT: - return "ESP_GAP_BLE_REMOVE_BOND_DEV_COMPLETE_EVT"; - - case ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT: - return "ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT"; - - case ESP_GAP_BLE_SCAN_RESULT_EVT: - return "ESP_GAP_BLE_SCAN_RESULT_EVT"; - - case ESP_GAP_BLE_SCAN_RSP_DATA_RAW_SET_COMPLETE_EVT: - return "ESP_GAP_BLE_SCAN_RSP_DATA_RAW_SET_COMPLETE_EVT"; - - case ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT: - return "ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT"; - - case ESP_GAP_BLE_SCAN_START_COMPLETE_EVT: - return "ESP_GAP_BLE_SCAN_START_COMPLETE_EVT"; - - case ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT: - return "ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT"; - - case ESP_GAP_BLE_SEC_REQ_EVT: /* BLE security request */ - return "ESP_GAP_BLE_SEC_REQ_EVT"; - - case ESP_GAP_BLE_SET_LOCAL_PRIVACY_COMPLETE_EVT: - return "ESP_GAP_BLE_SET_LOCAL_PRIVACY_COMPLETE_EVT"; - - case ESP_GAP_BLE_SET_PKT_LENGTH_COMPLETE_EVT: - return "ESP_GAP_BLE_SET_PKT_LENGTH_COMPLETE_EVT"; - - case ESP_GAP_BLE_SET_STATIC_RAND_ADDR_EVT: - return "ESP_GAP_BLE_SET_STATIC_RAND_ADDR_EVT"; - - case ESP_GAP_BLE_UPDATE_CONN_PARAMS_EVT: - return "ESP_GAP_BLE_UPDATE_CONN_PARAMS_EVT"; - - - default: - ESP_LOGD(LOG_TAG, "gapEventToString: Unknown event type %d 0x%.2x", eventType, eventType); - return "Unknown event type"; - } -} // gapEventToString - - -std::string BLEUtils::gattCharacteristicUUIDToString(uint32_t characteristicUUID) { - const characteristicMap_t *p = g_characteristicsMappings; - while (strlen(p->name) > 0) { - if (p->assignedNumber == characteristicUUID) { - return std::string(p->name); - } - p++; - } - return "Unknown"; -} // gattCharacteristicUUIDToString - - -/** - * @brief Given the UUID for a BLE defined descriptor, return its string representation. - * @param [in] descriptorUUID UUID of the descriptor to be returned as a string. - * @return The string representation of a descriptor UUID. - */ -std::string BLEUtils::gattDescriptorUUIDToString(uint32_t descriptorUUID) { - gattdescriptor_t* p = (gattdescriptor_t *)g_descriptor_ids; - while (strlen(p->name) > 0) { - if (p->assignedNumber == descriptorUUID) { - return std::string(p->name); - } - p++; - } - return ""; -} // gattDescriptorUUIDToString - - -/** - * @brief Return a string representation of an esp_gattc_service_elem_t. - * @return A string representation of an esp_gattc_service_elem_t. - */ -std::string BLEUtils::gattcServiceElementToString(esp_gattc_service_elem_t* pGATTCServiceElement) { - std::stringstream ss; - - ss << "[uuid: " << BLEUUID(pGATTCServiceElement->uuid).toString() << - ", start_handle: " << pGATTCServiceElement->start_handle << - " 0x" << std::hex << pGATTCServiceElement->start_handle << - ", end_handle: " << std::dec << pGATTCServiceElement->end_handle << - " 0x" << std::hex << pGATTCServiceElement->end_handle << "]"; - return ss.str(); -} // gattcServiceElementToString - - -/** - * @brief Convert an esp_gatt_srvc_id_t to a string. - */ -std::string BLEUtils::gattServiceIdToString(esp_gatt_srvc_id_t srvcId) { - return gattIdToString(srvcId.id); -} // gattServiceIdToString - - -std::string BLEUtils::gattServiceToString(uint32_t serviceId) { - gattService_t* p = (gattService_t *)g_gattServices; - while (strlen(p->name) > 0) { - if (p->assignedNumber == serviceId) { - return std::string(p->name); - } - p++; - } - return "Unknown"; -} // gattServiceToString - - -/** - * @brief Convert a GATT status to a string. - * - * @param [in] status The status to convert. - * @return A string representation of the status. - */ -std::string BLEUtils::gattStatusToString(esp_gatt_status_t status) { - switch(status) { - case ESP_GATT_OK: - return "ESP_GATT_OK"; - case ESP_GATT_INVALID_HANDLE: - return "ESP_GATT_INVALID_HANDLE"; - case ESP_GATT_READ_NOT_PERMIT: - return "ESP_GATT_READ_NOT_PERMIT"; - case ESP_GATT_WRITE_NOT_PERMIT: - return "ESP_GATT_WRITE_NOT_PERMIT"; - case ESP_GATT_INVALID_PDU: - return "ESP_GATT_INVALID_PDU"; - case ESP_GATT_INSUF_AUTHENTICATION: - return "ESP_GATT_INSUF_AUTHENTICATION"; - case ESP_GATT_REQ_NOT_SUPPORTED: - return "ESP_GATT_REQ_NOT_SUPPORTED"; - case ESP_GATT_INVALID_OFFSET: - return "ESP_GATT_INVALID_OFFSET"; - case ESP_GATT_INSUF_AUTHORIZATION: - return "ESP_GATT_INSUF_AUTHORIZATION"; - case ESP_GATT_PREPARE_Q_FULL: - return "ESP_GATT_PREPARE_Q_FULL"; - case ESP_GATT_NOT_FOUND: - return "ESP_GATT_NOT_FOUND"; - case ESP_GATT_NOT_LONG: - return "ESP_GATT_NOT_LONG"; - case ESP_GATT_INSUF_KEY_SIZE: - return "ESP_GATT_INSUF_KEY_SIZE"; - case ESP_GATT_INVALID_ATTR_LEN: - return "ESP_GATT_INVALID_ATTR_LEN"; - case ESP_GATT_ERR_UNLIKELY: - return "ESP_GATT_ERR_UNLIKELY"; - case ESP_GATT_INSUF_ENCRYPTION: - return "ESP_GATT_INSUF_ENCRYPTION"; - case ESP_GATT_UNSUPPORT_GRP_TYPE: - return "ESP_GATT_UNSUPPORT_GRP_TYPE"; - case ESP_GATT_INSUF_RESOURCE: - return "ESP_GATT_INSUF_RESOURCE"; - case ESP_GATT_NO_RESOURCES: - return "ESP_GATT_NO_RESOURCES"; - case ESP_GATT_INTERNAL_ERROR: - return "ESP_GATT_INTERNAL_ERROR"; - case ESP_GATT_WRONG_STATE: - return "ESP_GATT_WRONG_STATE"; - case ESP_GATT_DB_FULL: - return "ESP_GATT_DB_FULL"; - case ESP_GATT_BUSY: - return "ESP_GATT_BUSY"; - case ESP_GATT_ERROR: - return "ESP_GATT_ERROR"; - case ESP_GATT_CMD_STARTED: - return "ESP_GATT_CMD_STARTED"; - case ESP_GATT_ILLEGAL_PARAMETER: - return "ESP_GATT_ILLEGAL_PARAMETER"; - case ESP_GATT_PENDING: - return "ESP_GATT_PENDING"; - case ESP_GATT_AUTH_FAIL: - return "ESP_GATT_AUTH_FAIL"; - case ESP_GATT_MORE: - return "ESP_GATT_MORE"; - case ESP_GATT_INVALID_CFG: - return "ESP_GATT_INVALID_CFG"; - case ESP_GATT_SERVICE_STARTED: - return "ESP_GATT_SERVICE_STARTED"; - case ESP_GATT_ENCRYPED_NO_MITM: - return "ESP_GATT_ENCRYPED_NO_MITM"; - case ESP_GATT_NOT_ENCRYPTED: - return "ESP_GATT_NOT_ENCRYPTED"; - case ESP_GATT_CONGESTED: - return "ESP_GATT_CONGESTED"; - case ESP_GATT_DUP_REG: - return "ESP_GATT_DUP_REG"; - case ESP_GATT_ALREADY_OPEN: - return "ESP_GATT_ALREADY_OPEN"; - case ESP_GATT_CANCEL: - return "ESP_GATT_CANCEL"; - case ESP_GATT_STACK_RSP: - return "ESP_GATT_STACK_RSP"; - case ESP_GATT_APP_RSP: - return "ESP_GATT_APP_RSP"; - case ESP_GATT_UNKNOWN_ERROR: - return "ESP_GATT_UNKNOWN_ERROR"; - case ESP_GATT_CCC_CFG_ERR: - return "ESP_GATT_CCC_CFG_ERR"; - case ESP_GATT_PRC_IN_PROGRESS: - return "ESP_GATT_PRC_IN_PROGRESS"; - case ESP_GATT_OUT_OF_RANGE: - return "ESP_GATT_OUT_OF_RANGE"; - default: - return "Unknown"; - } -} // gattStatusToString - - - -std::string BLEUtils::getMember(uint32_t memberId) { - member_t* p = (member_t *)members_ids; - - while (strlen(p->name) > 0) { - if (p->assignedNumber == memberId) { - return std::string(p->name); - } - p++; - } - return "Unknown"; -} - -/** - * @brief convert a GAP search event to a string. - * @param [in] searchEvt - * @return The search event type as a string. - */ -const char* BLEUtils::searchEventTypeToString(esp_gap_search_evt_t searchEvt) { - switch(searchEvt) { - case ESP_GAP_SEARCH_INQ_RES_EVT: - return "ESP_GAP_SEARCH_INQ_RES_EVT"; - case ESP_GAP_SEARCH_INQ_CMPL_EVT: - return "ESP_GAP_SEARCH_INQ_CMPL_EVT"; - case ESP_GAP_SEARCH_DISC_RES_EVT: - return "ESP_GAP_SEARCH_DISC_RES_EVT"; - case ESP_GAP_SEARCH_DISC_BLE_RES_EVT: - return "ESP_GAP_SEARCH_DISC_BLE_RES_EVT"; - case ESP_GAP_SEARCH_DISC_CMPL_EVT: - return "ESP_GAP_SEARCH_DISC_CMPL_EVT"; - case ESP_GAP_SEARCH_DI_DISC_CMPL_EVT: - return "ESP_GAP_SEARCH_DI_DISC_CMPL_EVT"; - case ESP_GAP_SEARCH_SEARCH_CANCEL_CMPL_EVT: - return "ESP_GAP_SEARCH_SEARCH_CANCEL_CMPL_EVT"; - default: - ESP_LOGD(LOG_TAG, "Unknown event type: 0x%x", searchEvt); - return "Unknown event type"; - } -} // searchEventTypeToString - -#endif // CONFIG_BT_ENABLED diff --git a/lib/ESP32_BLE_Arduino/src/BLEUtils.h b/lib/ESP32_BLE_Arduino/src/BLEUtils.h deleted file mode 100644 index b2baee53..00000000 --- a/lib/ESP32_BLE_Arduino/src/BLEUtils.h +++ /dev/null @@ -1,63 +0,0 @@ -/* - * BLEUtils.h - * - * Created on: Mar 25, 2017 - * Author: kolban - */ - -#ifndef COMPONENTS_CPP_UTILS_BLEUTILS_H_ -#define COMPONENTS_CPP_UTILS_BLEUTILS_H_ -#include "sdkconfig.h" -#if defined(CONFIG_BT_ENABLED) -#include // ESP32 BLE -#include // ESP32 BLE -#include // ESP32 BLE -#include -#include "BLEClient.h" - -/** - * @brief A set of general %BLE utilities. - */ -class BLEUtils { -public: - static const char* addressTypeToString(esp_ble_addr_type_t type); - static std::string adFlagsToString(uint8_t adFlags); - static const char* advTypeToString(uint8_t advType); - static esp_gatt_id_t buildGattId(esp_bt_uuid_t uuid, uint8_t inst_id=0); - static esp_gatt_srvc_id_t buildGattSrvcId(esp_gatt_id_t gattId, bool is_primary=true); - static char* buildHexData(uint8_t* target, uint8_t* source, uint8_t length); - static std::string buildPrintData(uint8_t* source, size_t length); - static std::string characteristicPropertiesToString(esp_gatt_char_prop_t prop); - static const char* devTypeToString(esp_bt_dev_type_t type); - static void dumpGapEvent( - esp_gap_ble_cb_event_t event, - esp_ble_gap_cb_param_t* param); - static void dumpGattClientEvent( - esp_gattc_cb_event_t event, - esp_gatt_if_t gattc_if, - esp_ble_gattc_cb_param_t* evtParam); - static void dumpGattServerEvent( - esp_gatts_cb_event_t event, - esp_gatt_if_t gatts_if, - esp_ble_gatts_cb_param_t* evtParam); - static const char* eventTypeToString(esp_ble_evt_type_t eventType); - static BLEClient* findByAddress(BLEAddress address); - static BLEClient* findByConnId(uint16_t conn_id); - static const char* gapEventToString(uint32_t eventType); - static std::string gattCharacteristicUUIDToString(uint32_t characteristicUUID); - static std::string gattClientEventTypeToString(esp_gattc_cb_event_t eventType); - static std::string gattCloseReasonToString(esp_gatt_conn_reason_t reason); - static std::string gattcServiceElementToString(esp_gattc_service_elem_t *pGATTCServiceElement); - static std::string gattDescriptorUUIDToString(uint32_t descriptorUUID); - static std::string gattServerEventTypeToString(esp_gatts_cb_event_t eventType); - static std::string gattServiceIdToString(esp_gatt_srvc_id_t srvcId); - static std::string gattServiceToString(uint32_t serviceId); - static std::string gattStatusToString(esp_gatt_status_t status); - static std::string getMember(uint32_t memberId); - static void registerByAddress(BLEAddress address, BLEClient* pDevice); - static void registerByConnId(uint16_t conn_id, BLEClient* pDevice); - static const char* searchEventTypeToString(esp_gap_search_evt_t searchEvt); -}; - -#endif // CONFIG_BT_ENABLED -#endif /* COMPONENTS_CPP_UTILS_BLEUTILS_H_ */ diff --git a/lib/ESP32_BLE_Arduino/src/BLEValue.cpp b/lib/ESP32_BLE_Arduino/src/BLEValue.cpp deleted file mode 100644 index 49818e27..00000000 --- a/lib/ESP32_BLE_Arduino/src/BLEValue.cpp +++ /dev/null @@ -1,142 +0,0 @@ -/* - * BLEValue.cpp - * - * Created on: Jul 17, 2017 - * Author: kolban - */ -#include "sdkconfig.h" -#if defined(CONFIG_BT_ENABLED) - -#include - -#include "BLEValue.h" -#ifdef ARDUINO_ARCH_ESP32 -#include "esp32-hal-log.h" -#endif - -static const char* LOG_TAG="BLEValue"; - -BLEValue::BLEValue() { - m_accumulation = ""; - m_value = ""; - m_readOffset = 0; -} // BLEValue - - -/** - * @brief Add a message part to the accumulation. - * The accumulation is a growing set of data that is added to until a commit or cancel. - * @param [in] part A message part being added. - */ -void BLEValue::addPart(std::string part) { - ESP_LOGD(LOG_TAG, ">> addPart: length=%d", part.length()); - m_accumulation += part; -} // addPart - - -/** - * @brief Add a message part to the accumulation. - * The accumulation is a growing set of data that is added to until a commit or cancel. - * @param [in] pData A message part being added. - * @param [in] length The number of bytes being added. - */ -void BLEValue::addPart(uint8_t* pData, size_t length) { - ESP_LOGD(LOG_TAG, ">> addPart: length=%d", length); - m_accumulation += std::string((char *)pData, length); -} // addPart - - -/** - * @brief Cancel the current accumulation. - */ -void BLEValue::cancel() { - ESP_LOGD(LOG_TAG, ">> cancel"); - m_accumulation = ""; - m_readOffset = 0; -} // cancel - - -/** - * @brief Commit the current accumulation. - * When writing a value, we may find that we write it in "parts" meaning that the writes come in in pieces - * of the overall message. After the last part has been received, we may perform a commit which means that - * we now have the complete message and commit the change as a unit. - */ -void BLEValue::commit() { - ESP_LOGD(LOG_TAG, ">> commit"); - // If there is nothing to commit, do nothing. - if (m_accumulation.length() == 0) { - return; - } - setValue(m_accumulation); - m_accumulation = ""; - m_readOffset = 0; -} // commit - - -/** - * @brief Get a pointer to the data. - * @return A pointer to the data. - */ -uint8_t* BLEValue::getData() { - return (uint8_t*)m_value.data(); -} - - -/** - * @brief Get the length of the data in bytes. - * @return The length of the data in bytes. - */ -size_t BLEValue::getLength() { - return m_value.length(); -} // getLength - - -/** - * @brief Get the read offset. - * @return The read offset into the read. - */ -uint16_t BLEValue::getReadOffset() { - return m_readOffset; -} // getReadOffset - - -/** - * @brief Get the current value. - */ -std::string BLEValue::getValue() { - return m_value; -} // getValue - - -/** - * @brief Set the read offset - * @param [in] readOffset The offset into the read. - */ -void BLEValue::setReadOffset(uint16_t readOffset) { - m_readOffset = readOffset; -} // setReadOffset - - -/** - * @brief Set the current value. - */ -void BLEValue::setValue(std::string value) { - m_value = value; -} // setValue - - -/** - * @brief Set the current value. - * @param [in] pData The data for the current value. - * @param [in] The length of the new current value. - */ -void BLEValue::setValue(uint8_t* pData, size_t length) { - m_value = std::string((char*)pData, length); -} // setValue - - - - - -#endif // CONFIG_BT_ENABLED diff --git a/lib/ESP32_BLE_Arduino/src/BLEValue.h b/lib/ESP32_BLE_Arduino/src/BLEValue.h deleted file mode 100644 index 92a7f9a4..00000000 --- a/lib/ESP32_BLE_Arduino/src/BLEValue.h +++ /dev/null @@ -1,38 +0,0 @@ -/* - * BLEValue.h - * - * Created on: Jul 17, 2017 - * Author: kolban - */ - -#ifndef COMPONENTS_CPP_UTILS_BLEVALUE_H_ -#define COMPONENTS_CPP_UTILS_BLEVALUE_H_ -#include "sdkconfig.h" -#if defined(CONFIG_BT_ENABLED) -#include - -/** - * @brief The model of a %BLE value. - */ -class BLEValue { -public: - BLEValue(); - void addPart(std::string part); - void addPart(uint8_t* pData, size_t length); - void cancel(); - void commit(); - uint8_t* getData(); - size_t getLength(); - uint16_t getReadOffset(); - std::string getValue(); - void setReadOffset(uint16_t readOffset); - void setValue(std::string value); - void setValue(uint8_t* pData, size_t length); - -private: - std::string m_accumulation; - uint16_t m_readOffset; - std::string m_value; -}; -#endif // CONFIG_BT_ENABLED -#endif /* COMPONENTS_CPP_UTILS_BLEVALUE_H_ */ diff --git a/lib/ESP32_BLE_Arduino/src/FreeRTOS.cpp b/lib/ESP32_BLE_Arduino/src/FreeRTOS.cpp deleted file mode 100644 index 1ae01d73..00000000 --- a/lib/ESP32_BLE_Arduino/src/FreeRTOS.cpp +++ /dev/null @@ -1,286 +0,0 @@ -/* - * FreeRTOS.cpp - * - * Created on: Feb 24, 2017 - * Author: kolban - */ -#include // Include the base FreeRTOS definitions -#include // Include the task definitions -#include // Include the semaphore definitions -#include -#include -#include -#include "FreeRTOS.h" -#include -#include "sdkconfig.h" - -static const char* LOG_TAG = "FreeRTOS"; - -/** - * Sleep for the specified number of milliseconds. - * @param[in] ms The period in milliseconds for which to sleep. - */ -void FreeRTOS::sleep(uint32_t ms) { - ::vTaskDelay(ms/portTICK_PERIOD_MS); -} // sleep - - -/** - * Start a new task. - * @param[in] task The function pointer to the function to be run in the task. - * @param[in] taskName A string identifier for the task. - * @param[in] param An optional parameter to be passed to the started task. - * @param[in] stackSize An optional paremeter supplying the size of the stack in which to run the task. - */ -void FreeRTOS::startTask(void task(void*), std::string taskName, void *param, int stackSize) { - ::xTaskCreate(task, taskName.data(), stackSize, param, 5, NULL); -} // startTask - - -/** - * Delete the task. - * @param[in] pTask An optional handle to the task to be deleted. If not supplied the calling task will be deleted. - */ -void FreeRTOS::deleteTask(TaskHandle_t pTask) { - ::vTaskDelete(pTask); -} // deleteTask - - -/** - * Get the time in milliseconds since the %FreeRTOS scheduler started. - * @return The time in milliseconds since the %FreeRTOS scheduler started. - */ -uint32_t FreeRTOS::getTimeSinceStart() { - return (uint32_t)(xTaskGetTickCount()*portTICK_PERIOD_MS); -} // getTimeSinceStart - -/* - * public: - Semaphore(std::string = ""); - ~Semaphore(); - void give(); - void take(std::string owner=""); - void take(uint32_t timeoutMs, std::string owner=""); - private: - SemaphoreHandle_t m_semaphore; - std::string m_name; - std::string m_owner; - }; - * - */ - -/** - * @brief Wait for a semaphore to be released by trying to take it and - * then releasing it again. - * @param [in] owner A debug tag. - * @return The value associated with the semaphore. - */ -uint32_t FreeRTOS::Semaphore::wait(std::string owner) { - ESP_LOGV(LOG_TAG, ">> wait: Semaphore waiting: %s for %s", toString().c_str(), owner.c_str()); - - - if (m_usePthreads) { - pthread_mutex_lock(&m_pthread_mutex); - } else { - xSemaphoreTake(m_semaphore, portMAX_DELAY); - } - - m_owner = owner; - - if (m_usePthreads) { - pthread_mutex_unlock(&m_pthread_mutex); - } else { - xSemaphoreGive(m_semaphore); - } - - ESP_LOGV(LOG_TAG, "<< wait: Semaphore released: %s", toString().c_str()); - m_owner = std::string(""); - return m_value; -} // wait - - -FreeRTOS::Semaphore::Semaphore(std::string name) { - m_usePthreads = false; // Are we using pThreads or FreeRTOS? - if (m_usePthreads) { - pthread_mutex_init(&m_pthread_mutex, nullptr); - } else { - m_semaphore = xSemaphoreCreateMutex(); - } - - m_name = name; - m_owner = std::string(""); - m_value = 0; -} - - -FreeRTOS::Semaphore::~Semaphore() { - if (m_usePthreads) { - pthread_mutex_destroy(&m_pthread_mutex); - } else { - vSemaphoreDelete(m_semaphore); - } -} - - -/** - * @brief Give a semaphore. - * The Semaphore is given. - */ -void FreeRTOS::Semaphore::give() { - ESP_LOGV(LOG_TAG, "Semaphore giving: %s", toString().c_str()); - if (m_usePthreads) { - pthread_mutex_unlock(&m_pthread_mutex); - } else { - xSemaphoreGive(m_semaphore); - } -// #ifdef ARDUINO_ARCH_ESP32 -// FreeRTOS::sleep(10); -// #endif - - m_owner = std::string(""); -} // Semaphore::give - - -/** - * @brief Give a semaphore. - * The Semaphore is given with an associated value. - * @param [in] value The value to associate with the semaphore. - */ -void FreeRTOS::Semaphore::give(uint32_t value) { - m_value = value; - give(); -} // give - - -/** - * @brief Give a semaphore from an ISR. - */ -void FreeRTOS::Semaphore::giveFromISR() { - BaseType_t higherPriorityTaskWoken; - if (m_usePthreads) { - assert(false); - } else { - xSemaphoreGiveFromISR(m_semaphore, &higherPriorityTaskWoken); - } -} // giveFromISR - - -/** - * @brief Take a semaphore. - * Take a semaphore and wait indefinitely. - * @param [in] owner The new owner (for debugging) - * @return True if we took the semaphore. - */ -bool FreeRTOS::Semaphore::take(std::string owner) -{ - ESP_LOGD(LOG_TAG, "Semaphore taking: %s for %s", toString().c_str(), owner.c_str()); - bool rc = false; - if (m_usePthreads) { - pthread_mutex_lock(&m_pthread_mutex); - } else { - rc = ::xSemaphoreTake(m_semaphore, portMAX_DELAY); - } - m_owner = owner; - if (rc) { - ESP_LOGD(LOG_TAG, "Semaphore taken: %s", toString().c_str()); - } else { - ESP_LOGE(LOG_TAG, "Semaphore NOT taken: %s", toString().c_str()); - } - return rc; -} // Semaphore::take - - -/** - * @brief Take a semaphore. - * Take a semaphore but return if we haven't obtained it in the given period of milliseconds. - * @param [in] timeoutMs Timeout in milliseconds. - * @param [in] owner The new owner (for debugging) - * @return True if we took the semaphore. - */ -bool FreeRTOS::Semaphore::take(uint32_t timeoutMs, std::string owner) { - - ESP_LOGV(LOG_TAG, "Semaphore taking: %s for %s", toString().c_str(), owner.c_str()); - bool rc = false; - if (m_usePthreads) { - assert(false); // We apparently don't have a timed wait for pthreads. - } else { - rc = ::xSemaphoreTake(m_semaphore, timeoutMs/portTICK_PERIOD_MS); - } - m_owner = owner; - if (rc) { - ESP_LOGV(LOG_TAG, "Semaphore taken: %s", toString().c_str()); - } else { - ESP_LOGE(LOG_TAG, "Semaphore NOT taken: %s", toString().c_str()); - } - return rc; -} // Semaphore::take - - - -/** - * @brief Create a string representation of the semaphore. - * @return A string representation of the semaphore. - */ -std::string FreeRTOS::Semaphore::toString() { - std::stringstream stringStream; - stringStream << "name: "<< m_name << " (0x" << std::hex << std::setfill('0') << (uint32_t)m_semaphore << "), owner: " << m_owner; - return stringStream.str(); -} // toString - - -/** - * @brief Set the name of the semaphore. - * @param [in] name The name of the semaphore. - */ -void FreeRTOS::Semaphore::setName(std::string name) { - m_name = name; -} // setName - - -/** - * @brief Create a ring buffer. - * @param [in] length The amount of storage to allocate for the ring buffer. - * @param [in] type The type of buffer. One of RINGBUF_TYPE_NOSPLIT, RINGBUF_TYPE_ALLOWSPLIT, RINGBUF_TYPE_BYTEBUF. - */ -Ringbuffer::Ringbuffer(size_t length, ringbuf_type_t type) { - m_handle = ::xRingbufferCreate(length, type); -} // Ringbuffer - - -Ringbuffer::~Ringbuffer() { - ::vRingbufferDelete(m_handle); -} // ~Ringbuffer - - -/** - * @brief Receive data from the buffer. - * @param [out] size On return, the size of data returned. - * @param [in] wait How long to wait. - * @return A pointer to the storage retrieved. - */ -void* Ringbuffer::receive(size_t* size, TickType_t wait) { - return ::xRingbufferReceive(m_handle, size, wait); -} // receive - - -/** - * @brief Return an item. - * @param [in] item The item to be returned/released. - */ -void Ringbuffer::returnItem(void* item) { - ::vRingbufferReturnItem(m_handle, item); -} // returnItem - - -/** - * @brief Send data to the buffer. - * @param [in] data The data to place into the buffer. - * @param [in] length The length of data to place into the buffer. - * @param [in] wait How long to wait before giving up. The default is to wait indefinitely. - * @return - */ -uint32_t Ringbuffer::send(void* data, size_t length, TickType_t wait) { - return ::xRingbufferSend(m_handle, data, length, wait); -} // send - - diff --git a/lib/ESP32_BLE_Arduino/src/FreeRTOS.h b/lib/ESP32_BLE_Arduino/src/FreeRTOS.h deleted file mode 100644 index ab0e83d8..00000000 --- a/lib/ESP32_BLE_Arduino/src/FreeRTOS.h +++ /dev/null @@ -1,70 +0,0 @@ -/* - * FreeRTOS.h - * - * Created on: Feb 24, 2017 - * Author: kolban - */ - -#ifndef MAIN_FREERTOS_H_ -#define MAIN_FREERTOS_H_ -#include -#include -#include - -#include // Include the base FreeRTOS definitions. -#include // Include the task definitions. -#include // Include the semaphore definitions. -#include // Include the ringbuffer definitions. - - -/** - * @brief Interface to %FreeRTOS functions. - */ -class FreeRTOS { -public: - static void sleep(uint32_t ms); - static void startTask(void task(void *), std::string taskName, void *param=nullptr, int stackSize = 2048); - static void deleteTask(TaskHandle_t pTask = nullptr); - - static uint32_t getTimeSinceStart(); - - class Semaphore { - public: - Semaphore(std::string owner = ""); - ~Semaphore(); - void give(); - void give(uint32_t value); - void giveFromISR(); - void setName(std::string name); - bool take(std::string owner=""); - bool take(uint32_t timeoutMs, std::string owner=""); - std::string toString(); - uint32_t wait(std::string owner=""); - - private: - SemaphoreHandle_t m_semaphore; - pthread_mutex_t m_pthread_mutex; - std::string m_name; - std::string m_owner; - uint32_t m_value; - bool m_usePthreads; - }; -}; - - -/** - * @brief Ringbuffer. - */ -class Ringbuffer { -public: - Ringbuffer(size_t length, ringbuf_type_t type = RINGBUF_TYPE_NOSPLIT); - ~Ringbuffer(); - - void* receive(size_t* size, TickType_t wait = portMAX_DELAY); - void returnItem(void* item); - uint32_t send(void* data, size_t length, TickType_t wait = portMAX_DELAY); -private: - RingbufHandle_t m_handle; -}; - -#endif /* MAIN_FREERTOS_H_ */ diff --git a/lib/ESP32_BLE_Arduino/src/GeneralUtils.cpp b/lib/ESP32_BLE_Arduino/src/GeneralUtils.cpp deleted file mode 100644 index ccf74f79..00000000 --- a/lib/ESP32_BLE_Arduino/src/GeneralUtils.cpp +++ /dev/null @@ -1,465 +0,0 @@ -/* - * GeneralUtils.cpp - * - * Created on: May 20, 2017 - * Author: kolban - */ - -#include "GeneralUtils.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -static const char* LOG_TAG = "GeneralUtils"; - -static const char kBase64Alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "abcdefghijklmnopqrstuvwxyz" - "0123456789+/"; - -static int base64EncodedLength(size_t length) { - return (length + 2 - ((length + 2) % 3)) / 3 * 4; -} // base64EncodedLength - - -static int base64EncodedLength(const std::string &in) { - return base64EncodedLength(in.length()); -} // base64EncodedLength - - -static void a3_to_a4(unsigned char * a4, unsigned char * a3) { - a4[0] = (a3[0] & 0xfc) >> 2; - a4[1] = ((a3[0] & 0x03) << 4) + ((a3[1] & 0xf0) >> 4); - a4[2] = ((a3[1] & 0x0f) << 2) + ((a3[2] & 0xc0) >> 6); - a4[3] = (a3[2] & 0x3f); -} // a3_to_a4 - - -static void a4_to_a3(unsigned char * a3, unsigned char * a4) { - a3[0] = (a4[0] << 2) + ((a4[1] & 0x30) >> 4); - a3[1] = ((a4[1] & 0xf) << 4) + ((a4[2] & 0x3c) >> 2); - a3[2] = ((a4[2] & 0x3) << 6) + a4[3]; -} // a4_to_a3 - - -/** - * @brief Encode a string into base 64. - * @param [in] in - * @param [out] out - */ -bool GeneralUtils::base64Encode(const std::string &in, std::string *out) { - int i = 0, j = 0; - size_t enc_len = 0; - unsigned char a3[3]; - unsigned char a4[4]; - - out->resize(base64EncodedLength(in)); - - int input_len = in.size(); - std::string::const_iterator input = in.begin(); - - while (input_len--) { - a3[i++] = *(input++); - if (i == 3) { - a3_to_a4(a4, a3); - - for (i = 0; i < 4; i++) { - (*out)[enc_len++] = kBase64Alphabet[a4[i]]; - } - - i = 0; - } - } - - if (i) { - for (j = i; j < 3; j++) { - a3[j] = '\0'; - } - - a3_to_a4(a4, a3); - - for (j = 0; j < i + 1; j++) { - (*out)[enc_len++] = kBase64Alphabet[a4[j]]; - } - - while ((i++ < 3)) { - (*out)[enc_len++] = '='; - } - } - - return (enc_len == out->size()); -} // base64Encode - - -/** - * @brief Dump general info to the log. - * Data includes: - * * Amount of free RAM - */ -void GeneralUtils::dumpInfo() { - size_t freeHeap = heap_caps_get_free_size(MALLOC_CAP_8BIT); - esp_chip_info_t chipInfo; - esp_chip_info(&chipInfo); - ESP_LOGD(LOG_TAG, "--- dumpInfo ---"); - ESP_LOGD(LOG_TAG, "Free heap: %d", freeHeap); - ESP_LOGD(LOG_TAG, "Chip Info: Model: %d, cores: %d, revision: %d", chipInfo.model, chipInfo.cores, chipInfo.revision); - ESP_LOGD(LOG_TAG, "ESP-IDF version: %s", esp_get_idf_version()); - ESP_LOGD(LOG_TAG, "---"); -} // dumpInfo - - -/** - * @brief Does the string end with a specific character? - * @param [in] str The string to examine. - * @param [in] c The character to look form. - * @return True if the string ends with the given character. - */ -bool GeneralUtils::endsWith(std::string str, char c) { - if (str.empty()) { - return false; - } - if (str.at(str.length()-1) == c) { - return true; - } - return false; -} // endsWidth - - -static int DecodedLength(const std::string &in) { - int numEq = 0; - int n = in.size(); - - for (std::string::const_reverse_iterator it = in.rbegin(); *it == '='; ++it) { - ++numEq; - } - return ((6 * n) / 8) - numEq; -} // DecodedLength - - -static unsigned char b64_lookup(unsigned char c) { - if(c >='A' && c <='Z') return c - 'A'; - if(c >='a' && c <='z') return c - 71; - if(c >='0' && c <='9') return c + 4; - if(c == '+') return 62; - if(c == '/') return 63; - return 255; -}; // b64_lookup - - -/** - * @brief Decode a chunk of data that is base64 encoded. - * @param [in] in The string to be decoded. - * @param [out] out The resulting data. - */ -bool GeneralUtils::base64Decode(const std::string &in, std::string *out) { - int i = 0, j = 0; - size_t dec_len = 0; - unsigned char a3[3]; - unsigned char a4[4]; - - int input_len = in.size(); - std::string::const_iterator input = in.begin(); - - out->resize(DecodedLength(in)); - - while (input_len--) { - if (*input == '=') { - break; - } - - a4[i++] = *(input++); - if (i == 4) { - for (i = 0; i <4; i++) { - a4[i] = b64_lookup(a4[i]); - } - - a4_to_a3(a3,a4); - - for (i = 0; i < 3; i++) { - (*out)[dec_len++] = a3[i]; - } - - i = 0; - } - } - - if (i) { - for (j = i; j < 4; j++) { - a4[j] = '\0'; - } - - for (j = 0; j < 4; j++) { - a4[j] = b64_lookup(a4[j]); - } - - a4_to_a3(a3,a4); - - for (j = 0; j < i - 1; j++) { - (*out)[dec_len++] = a3[j]; - } - } - - return (dec_len == out->size()); - } // base64Decode - -/* -void GeneralUtils::hexDump(uint8_t* pData, uint32_t length) { - uint32_t index=0; - std::stringstream ascii; - std::stringstream hex; - char asciiBuf[80]; - char hexBuf[80]; - hex.str(""); - ascii.str(""); - while(index < length) { - hex << std::setfill('0') << std::setw(2) << std::hex << (int)pData[index] << ' '; - if (std::isprint(pData[index])) { - ascii << pData[index]; - } else { - ascii << '.'; - } - index++; - if (index % 16 == 0) { - strcpy(hexBuf, hex.str().c_str()); - strcpy(asciiBuf, ascii.str().c_str()); - ESP_LOGD(tag, "%s %s", hexBuf, asciiBuf); - hex.str(""); - ascii.str(""); - } - } - if (index %16 != 0) { - while(index % 16 != 0) { - hex << " "; - index++; - } - strcpy(hexBuf, hex.str().c_str()); - strcpy(asciiBuf, ascii.str().c_str()); - ESP_LOGD(tag, "%s %s", hexBuf, asciiBuf); - //ESP_LOGD(tag, "%s %s", hex.str().c_str(), ascii.str().c_str()); - } - FreeRTOS::sleep(1000); -} -*/ - -/* -void GeneralUtils::hexDump(uint8_t* pData, uint32_t length) { - uint32_t index=0; - static std::stringstream ascii; - static std::stringstream hex; - hex.str(""); - ascii.str(""); - while(index < length) { - hex << std::setfill('0') << std::setw(2) << std::hex << (int)pData[index] << ' '; - if (std::isprint(pData[index])) { - ascii << pData[index]; - } else { - ascii << '.'; - } - index++; - if (index % 16 == 0) { - ESP_LOGD(tag, "%s %s", hex.str().c_str(), ascii.str().c_str()); - hex.str(""); - ascii.str(""); - } - } - if (index %16 != 0) { - while(index % 16 != 0) { - hex << " "; - index++; - } - ESP_LOGD(tag, "%s %s", hex.str().c_str(), ascii.str().c_str()); - } - FreeRTOS::sleep(1000); -} -*/ - - -/** - * @brief Dump a representation of binary data to the console. - * - * @param [in] pData Pointer to the start of data to be logged. - * @param [in] length Length of the data (in bytes) to be logged. - * @return N/A. - */ -void GeneralUtils::hexDump(const uint8_t* pData, uint32_t length) { - char ascii[80]; - char hex[80]; - char tempBuf[80]; - uint32_t lineNumber = 0; - - ESP_LOGD(LOG_TAG, " 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f ----------------"); - strcpy(ascii, ""); - strcpy(hex, ""); - uint32_t index=0; - while(index < length) { - sprintf(tempBuf, "%.2x ", pData[index]); - strcat(hex, tempBuf); - if (isprint(pData[index])) { - sprintf(tempBuf, "%c", pData[index]); - } else { - sprintf(tempBuf, "."); - } - strcat(ascii, tempBuf); - index++; - if (index % 16 == 0) { - ESP_LOGD(LOG_TAG, "%.4x %s %s", lineNumber*16, hex, ascii); - strcpy(ascii, ""); - strcpy(hex, ""); - lineNumber++; - } - } - if (index %16 != 0) { - while(index % 16 != 0) { - strcat(hex, " "); - index++; - } - ESP_LOGD(LOG_TAG, "%.4x %s %s", lineNumber*16, hex, ascii); - } -} // hexDump - - -/** - * @brief Convert an IP address to string. - * @param ip The 4 byte IP address. - * @return A string representation of the IP address. - */ -std::string GeneralUtils::ipToString(uint8_t *ip) { - std::stringstream s; - s << (int)ip[0] << '.' << (int)ip[1] << '.' << (int)ip[2] << '.' << (int)ip[3]; - return s.str(); -} // ipToString - - -/** - * @brief Split a string into parts based on a delimiter. - * @param [in] source The source string to split. - * @param [in] delimiter The delimiter characters. - * @return A vector of strings that are the split of the input. - */ -std::vector GeneralUtils::split(std::string source, char delimiter) { - // See also: https://stackoverflow.com/questions/5167625/splitting-a-c-stdstring-using-tokens-e-g - std::vector strings; - std::istringstream iss(source); - std::string s; - while(std::getline(iss, s, delimiter)) { - strings.push_back(trim(s)); - } - return strings; -} // split - - -/** - * @brief Convert an ESP error code to a string. - * @param [in] errCode The errCode to be converted. - * @return A string representation of the error code. - */ -const char* GeneralUtils::errorToString(esp_err_t errCode) { - switch(errCode) { - case ESP_OK: - return "OK"; - case ESP_FAIL: - return "Fail"; - case ESP_ERR_NO_MEM: - return "No memory"; - case ESP_ERR_INVALID_ARG: - return "Invalid argument"; - case ESP_ERR_INVALID_SIZE: - return "Invalid state"; - case ESP_ERR_INVALID_STATE: - return "Invalid state"; - case ESP_ERR_NOT_FOUND: - return "Not found"; - case ESP_ERR_NOT_SUPPORTED: - return "Not supported"; - case ESP_ERR_TIMEOUT: - return "Timeout"; - case ESP_ERR_NVS_NOT_INITIALIZED: - return "ESP_ERR_NVS_NOT_INITIALIZED"; - case ESP_ERR_NVS_NOT_FOUND: - return "ESP_ERR_NVS_NOT_FOUND"; - case ESP_ERR_NVS_TYPE_MISMATCH: - return "ESP_ERR_NVS_TYPE_MISMATCH"; - case ESP_ERR_NVS_READ_ONLY: - return "ESP_ERR_NVS_READ_ONLY"; - case ESP_ERR_NVS_NOT_ENOUGH_SPACE: - return "ESP_ERR_NVS_NOT_ENOUGH_SPACE"; - case ESP_ERR_NVS_INVALID_NAME: - return "ESP_ERR_NVS_INVALID_NAME"; - case ESP_ERR_NVS_INVALID_HANDLE: - return "ESP_ERR_NVS_INVALID_HANDLE"; - case ESP_ERR_NVS_REMOVE_FAILED: - return "ESP_ERR_NVS_REMOVE_FAILED"; - case ESP_ERR_NVS_KEY_TOO_LONG: - return "ESP_ERR_NVS_KEY_TOO_LONG"; - case ESP_ERR_NVS_PAGE_FULL: - return "ESP_ERR_NVS_PAGE_FULL"; - case ESP_ERR_NVS_INVALID_STATE: - return "ESP_ERR_NVS_INVALID_STATE"; - case ESP_ERR_NVS_INVALID_LENGTH: - return "ESP_ERR_NVS_INVALID_LENGTH"; - case ESP_ERR_WIFI_NOT_INIT: - return "ESP_ERR_WIFI_NOT_INIT"; - //case ESP_ERR_WIFI_NOT_START: - // return "ESP_ERR_WIFI_NOT_START"; - case ESP_ERR_WIFI_IF: - return "ESP_ERR_WIFI_IF"; - case ESP_ERR_WIFI_MODE: - return "ESP_ERR_WIFI_MODE"; - case ESP_ERR_WIFI_STATE: - return "ESP_ERR_WIFI_STATE"; - case ESP_ERR_WIFI_CONN: - return "ESP_ERR_WIFI_CONN"; - case ESP_ERR_WIFI_NVS: - return "ESP_ERR_WIFI_NVS"; - case ESP_ERR_WIFI_MAC: - return "ESP_ERR_WIFI_MAC"; - case ESP_ERR_WIFI_SSID: - return "ESP_ERR_WIFI_SSID"; - case ESP_ERR_WIFI_PASSWORD: - return "ESP_ERR_WIFI_PASSWORD"; - case ESP_ERR_WIFI_TIMEOUT: - return "ESP_ERR_WIFI_TIMEOUT"; - case ESP_ERR_WIFI_WAKE_FAIL: - return "ESP_ERR_WIFI_WAKE_FAIL"; - } - return "Unknown ESP_ERR error"; -} // errorToString - - -/** - * @brief Convert a string to lower case. - * @param [in] value The string to convert to lower case. - * @return A lower case representation of the string. - */ -std::string GeneralUtils::toLower(std::string& value) { - // Question: Could this be improved with a signature of: - // std::string& GeneralUtils::toLower(std::string& value) - std::transform(value.begin(), value.end(), value.begin(), ::tolower); - return value; -} // toLower - - -/** - * @brief Remove white space from a string. - */ -std::string GeneralUtils::trim(const std::string& str) -{ - size_t first = str.find_first_not_of(' '); - if (std::string::npos == first) - { - return str; - } - size_t last = str.find_last_not_of(' '); - return str.substr(first, (last - first + 1)); -} // trim - - diff --git a/lib/ESP32_BLE_Arduino/src/GeneralUtils.h b/lib/ESP32_BLE_Arduino/src/GeneralUtils.h deleted file mode 100644 index 013953dc..00000000 --- a/lib/ESP32_BLE_Arduino/src/GeneralUtils.h +++ /dev/null @@ -1,34 +0,0 @@ -/* - * GeneralUtils.h - * - * Created on: May 20, 2017 - * Author: kolban - */ - -#ifndef COMPONENTS_CPP_UTILS_GENERALUTILS_H_ -#define COMPONENTS_CPP_UTILS_GENERALUTILS_H_ -#include -#include -#include -#include -#include - -/** - * @brief General utilities. - */ -class GeneralUtils { -public: - static bool base64Decode(const std::string& in, std::string* out); - static bool base64Encode(const std::string& in, std::string* out); - static void dumpInfo(); - static bool endsWith(std::string str, char c); - static const char* errorToString(esp_err_t errCode); - static void hexDump(const uint8_t* pData, uint32_t length); - static std::string ipToString(uint8_t* ip); - static std::vector split(std::string source, char delimiter); - static std::string toLower(std::string& value); - static std::string trim(const std::string& str); - -}; - -#endif /* COMPONENTS_CPP_UTILS_GENERALUTILS_H_ */ diff --git a/lib/ESP32_BLE_Arduino/src/HIDKeyboardTypes.h b/lib/ESP32_BLE_Arduino/src/HIDKeyboardTypes.h deleted file mode 100644 index ef48a526..00000000 --- a/lib/ESP32_BLE_Arduino/src/HIDKeyboardTypes.h +++ /dev/null @@ -1,402 +0,0 @@ -/* Copyright (c) 2015 mbed.org, MIT License - * - * 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. - * - * Note: this file was pulled from different parts of the USBHID library, in mbed SDK - */ - -#ifndef KEYBOARD_DEFS_H -#define KEYBOARD_DEFS_H - -#define REPORT_ID_KEYBOARD 1 -#define REPORT_ID_VOLUME 3 - -/* Modifiers */ -enum MODIFIER_KEY { - KEY_CTRL = 1, - KEY_SHIFT = 2, - KEY_ALT = 4, -}; - - -enum MEDIA_KEY { - KEY_NEXT_TRACK, /*!< next Track Button */ - KEY_PREVIOUS_TRACK, /*!< Previous track Button */ - KEY_STOP, /*!< Stop Button */ - KEY_PLAY_PAUSE, /*!< Play/Pause Button */ - KEY_MUTE, /*!< Mute Button */ - KEY_VOLUME_UP, /*!< Volume Up Button */ - KEY_VOLUME_DOWN, /*!< Volume Down Button */ -}; - -enum FUNCTION_KEY { - KEY_F1 = 128, /* F1 key */ - KEY_F2, /* F2 key */ - KEY_F3, /* F3 key */ - KEY_F4, /* F4 key */ - KEY_F5, /* F5 key */ - KEY_F6, /* F6 key */ - KEY_F7, /* F7 key */ - KEY_F8, /* F8 key */ - KEY_F9, /* F9 key */ - KEY_F10, /* F10 key */ - KEY_F11, /* F11 key */ - KEY_F12, /* F12 key */ - - KEY_PRINT_SCREEN, /* Print Screen key */ - KEY_SCROLL_LOCK, /* Scroll lock */ - KEY_CAPS_LOCK, /* caps lock */ - KEY_NUM_LOCK, /* num lock */ - KEY_INSERT, /* Insert key */ - KEY_HOME, /* Home key */ - KEY_PAGE_UP, /* Page Up key */ - KEY_PAGE_DOWN, /* Page Down key */ - - RIGHT_ARROW, /* Right arrow */ - LEFT_ARROW, /* Left arrow */ - DOWN_ARROW, /* Down arrow */ - UP_ARROW, /* Up arrow */ -}; - -typedef struct { - unsigned char usage; - unsigned char modifier; -} KEYMAP; - -#ifdef US_KEYBOARD -/* US keyboard (as HID standard) */ -#define KEYMAP_SIZE (152) -const KEYMAP keymap[KEYMAP_SIZE] = { - {0, 0}, /* NUL */ - {0, 0}, /* SOH */ - {0, 0}, /* STX */ - {0, 0}, /* ETX */ - {0, 0}, /* EOT */ - {0, 0}, /* ENQ */ - {0, 0}, /* ACK */ - {0, 0}, /* BEL */ - {0x2a, 0}, /* BS */ /* Keyboard Delete (Backspace) */ - {0x2b, 0}, /* TAB */ /* Keyboard Tab */ - {0x28, 0}, /* LF */ /* Keyboard Return (Enter) */ - {0, 0}, /* VT */ - {0, 0}, /* FF */ - {0, 0}, /* CR */ - {0, 0}, /* SO */ - {0, 0}, /* SI */ - {0, 0}, /* DEL */ - {0, 0}, /* DC1 */ - {0, 0}, /* DC2 */ - {0, 0}, /* DC3 */ - {0, 0}, /* DC4 */ - {0, 0}, /* NAK */ - {0, 0}, /* SYN */ - {0, 0}, /* ETB */ - {0, 0}, /* CAN */ - {0, 0}, /* EM */ - {0, 0}, /* SUB */ - {0, 0}, /* ESC */ - {0, 0}, /* FS */ - {0, 0}, /* GS */ - {0, 0}, /* RS */ - {0, 0}, /* US */ - {0x2c, 0}, /* */ - {0x1e, KEY_SHIFT}, /* ! */ - {0x34, KEY_SHIFT}, /* " */ - {0x20, KEY_SHIFT}, /* # */ - {0x21, KEY_SHIFT}, /* $ */ - {0x22, KEY_SHIFT}, /* % */ - {0x24, KEY_SHIFT}, /* & */ - {0x34, 0}, /* ' */ - {0x26, KEY_SHIFT}, /* ( */ - {0x27, KEY_SHIFT}, /* ) */ - {0x25, KEY_SHIFT}, /* * */ - {0x2e, KEY_SHIFT}, /* + */ - {0x36, 0}, /* , */ - {0x2d, 0}, /* - */ - {0x37, 0}, /* . */ - {0x38, 0}, /* / */ - {0x27, 0}, /* 0 */ - {0x1e, 0}, /* 1 */ - {0x1f, 0}, /* 2 */ - {0x20, 0}, /* 3 */ - {0x21, 0}, /* 4 */ - {0x22, 0}, /* 5 */ - {0x23, 0}, /* 6 */ - {0x24, 0}, /* 7 */ - {0x25, 0}, /* 8 */ - {0x26, 0}, /* 9 */ - {0x33, KEY_SHIFT}, /* : */ - {0x33, 0}, /* ; */ - {0x36, KEY_SHIFT}, /* < */ - {0x2e, 0}, /* = */ - {0x37, KEY_SHIFT}, /* > */ - {0x38, KEY_SHIFT}, /* ? */ - {0x1f, KEY_SHIFT}, /* @ */ - {0x04, KEY_SHIFT}, /* A */ - {0x05, KEY_SHIFT}, /* B */ - {0x06, KEY_SHIFT}, /* C */ - {0x07, KEY_SHIFT}, /* D */ - {0x08, KEY_SHIFT}, /* E */ - {0x09, KEY_SHIFT}, /* F */ - {0x0a, KEY_SHIFT}, /* G */ - {0x0b, KEY_SHIFT}, /* H */ - {0x0c, KEY_SHIFT}, /* I */ - {0x0d, KEY_SHIFT}, /* J */ - {0x0e, KEY_SHIFT}, /* K */ - {0x0f, KEY_SHIFT}, /* L */ - {0x10, KEY_SHIFT}, /* M */ - {0x11, KEY_SHIFT}, /* N */ - {0x12, KEY_SHIFT}, /* O */ - {0x13, KEY_SHIFT}, /* P */ - {0x14, KEY_SHIFT}, /* Q */ - {0x15, KEY_SHIFT}, /* R */ - {0x16, KEY_SHIFT}, /* S */ - {0x17, KEY_SHIFT}, /* T */ - {0x18, KEY_SHIFT}, /* U */ - {0x19, KEY_SHIFT}, /* V */ - {0x1a, KEY_SHIFT}, /* W */ - {0x1b, KEY_SHIFT}, /* X */ - {0x1c, KEY_SHIFT}, /* Y */ - {0x1d, KEY_SHIFT}, /* Z */ - {0x2f, 0}, /* [ */ - {0x31, 0}, /* \ */ - {0x30, 0}, /* ] */ - {0x23, KEY_SHIFT}, /* ^ */ - {0x2d, KEY_SHIFT}, /* _ */ - {0x35, 0}, /* ` */ - {0x04, 0}, /* a */ - {0x05, 0}, /* b */ - {0x06, 0}, /* c */ - {0x07, 0}, /* d */ - {0x08, 0}, /* e */ - {0x09, 0}, /* f */ - {0x0a, 0}, /* g */ - {0x0b, 0}, /* h */ - {0x0c, 0}, /* i */ - {0x0d, 0}, /* j */ - {0x0e, 0}, /* k */ - {0x0f, 0}, /* l */ - {0x10, 0}, /* m */ - {0x11, 0}, /* n */ - {0x12, 0}, /* o */ - {0x13, 0}, /* p */ - {0x14, 0}, /* q */ - {0x15, 0}, /* r */ - {0x16, 0}, /* s */ - {0x17, 0}, /* t */ - {0x18, 0}, /* u */ - {0x19, 0}, /* v */ - {0x1a, 0}, /* w */ - {0x1b, 0}, /* x */ - {0x1c, 0}, /* y */ - {0x1d, 0}, /* z */ - {0x2f, KEY_SHIFT}, /* { */ - {0x31, KEY_SHIFT}, /* | */ - {0x30, KEY_SHIFT}, /* } */ - {0x35, KEY_SHIFT}, /* ~ */ - {0,0}, /* DEL */ - - {0x3a, 0}, /* F1 */ - {0x3b, 0}, /* F2 */ - {0x3c, 0}, /* F3 */ - {0x3d, 0}, /* F4 */ - {0x3e, 0}, /* F5 */ - {0x3f, 0}, /* F6 */ - {0x40, 0}, /* F7 */ - {0x41, 0}, /* F8 */ - {0x42, 0}, /* F9 */ - {0x43, 0}, /* F10 */ - {0x44, 0}, /* F11 */ - {0x45, 0}, /* F12 */ - - {0x46, 0}, /* PRINT_SCREEN */ - {0x47, 0}, /* SCROLL_LOCK */ - {0x39, 0}, /* CAPS_LOCK */ - {0x53, 0}, /* NUM_LOCK */ - {0x49, 0}, /* INSERT */ - {0x4a, 0}, /* HOME */ - {0x4b, 0}, /* PAGE_UP */ - {0x4e, 0}, /* PAGE_DOWN */ - - {0x4f, 0}, /* RIGHT_ARROW */ - {0x50, 0}, /* LEFT_ARROW */ - {0x51, 0}, /* DOWN_ARROW */ - {0x52, 0}, /* UP_ARROW */ -}; - -#else -/* UK keyboard */ -#define KEYMAP_SIZE (152) -const KEYMAP keymap[KEYMAP_SIZE] = { - {0, 0}, /* NUL */ - {0, 0}, /* SOH */ - {0, 0}, /* STX */ - {0, 0}, /* ETX */ - {0, 0}, /* EOT */ - {0, 0}, /* ENQ */ - {0, 0}, /* ACK */ - {0, 0}, /* BEL */ - {0x2a, 0}, /* BS */ /* Keyboard Delete (Backspace) */ - {0x2b, 0}, /* TAB */ /* Keyboard Tab */ - {0x28, 0}, /* LF */ /* Keyboard Return (Enter) */ - {0, 0}, /* VT */ - {0, 0}, /* FF */ - {0, 0}, /* CR */ - {0, 0}, /* SO */ - {0, 0}, /* SI */ - {0, 0}, /* DEL */ - {0, 0}, /* DC1 */ - {0, 0}, /* DC2 */ - {0, 0}, /* DC3 */ - {0, 0}, /* DC4 */ - {0, 0}, /* NAK */ - {0, 0}, /* SYN */ - {0, 0}, /* ETB */ - {0, 0}, /* CAN */ - {0, 0}, /* EM */ - {0, 0}, /* SUB */ - {0, 0}, /* ESC */ - {0, 0}, /* FS */ - {0, 0}, /* GS */ - {0, 0}, /* RS */ - {0, 0}, /* US */ - {0x2c, 0}, /* */ - {0x1e, KEY_SHIFT}, /* ! */ - {0x1f, KEY_SHIFT}, /* " */ - {0x32, 0}, /* # */ - {0x21, KEY_SHIFT}, /* $ */ - {0x22, KEY_SHIFT}, /* % */ - {0x24, KEY_SHIFT}, /* & */ - {0x34, 0}, /* ' */ - {0x26, KEY_SHIFT}, /* ( */ - {0x27, KEY_SHIFT}, /* ) */ - {0x25, KEY_SHIFT}, /* * */ - {0x2e, KEY_SHIFT}, /* + */ - {0x36, 0}, /* , */ - {0x2d, 0}, /* - */ - {0x37, 0}, /* . */ - {0x38, 0}, /* / */ - {0x27, 0}, /* 0 */ - {0x1e, 0}, /* 1 */ - {0x1f, 0}, /* 2 */ - {0x20, 0}, /* 3 */ - {0x21, 0}, /* 4 */ - {0x22, 0}, /* 5 */ - {0x23, 0}, /* 6 */ - {0x24, 0}, /* 7 */ - {0x25, 0}, /* 8 */ - {0x26, 0}, /* 9 */ - {0x33, KEY_SHIFT}, /* : */ - {0x33, 0}, /* ; */ - {0x36, KEY_SHIFT}, /* < */ - {0x2e, 0}, /* = */ - {0x37, KEY_SHIFT}, /* > */ - {0x38, KEY_SHIFT}, /* ? */ - {0x34, KEY_SHIFT}, /* @ */ - {0x04, KEY_SHIFT}, /* A */ - {0x05, KEY_SHIFT}, /* B */ - {0x06, KEY_SHIFT}, /* C */ - {0x07, KEY_SHIFT}, /* D */ - {0x08, KEY_SHIFT}, /* E */ - {0x09, KEY_SHIFT}, /* F */ - {0x0a, KEY_SHIFT}, /* G */ - {0x0b, KEY_SHIFT}, /* H */ - {0x0c, KEY_SHIFT}, /* I */ - {0x0d, KEY_SHIFT}, /* J */ - {0x0e, KEY_SHIFT}, /* K */ - {0x0f, KEY_SHIFT}, /* L */ - {0x10, KEY_SHIFT}, /* M */ - {0x11, KEY_SHIFT}, /* N */ - {0x12, KEY_SHIFT}, /* O */ - {0x13, KEY_SHIFT}, /* P */ - {0x14, KEY_SHIFT}, /* Q */ - {0x15, KEY_SHIFT}, /* R */ - {0x16, KEY_SHIFT}, /* S */ - {0x17, KEY_SHIFT}, /* T */ - {0x18, KEY_SHIFT}, /* U */ - {0x19, KEY_SHIFT}, /* V */ - {0x1a, KEY_SHIFT}, /* W */ - {0x1b, KEY_SHIFT}, /* X */ - {0x1c, KEY_SHIFT}, /* Y */ - {0x1d, KEY_SHIFT}, /* Z */ - {0x2f, 0}, /* [ */ - {0x64, 0}, /* \ */ - {0x30, 0}, /* ] */ - {0x23, KEY_SHIFT}, /* ^ */ - {0x2d, KEY_SHIFT}, /* _ */ - {0x35, 0}, /* ` */ - {0x04, 0}, /* a */ - {0x05, 0}, /* b */ - {0x06, 0}, /* c */ - {0x07, 0}, /* d */ - {0x08, 0}, /* e */ - {0x09, 0}, /* f */ - {0x0a, 0}, /* g */ - {0x0b, 0}, /* h */ - {0x0c, 0}, /* i */ - {0x0d, 0}, /* j */ - {0x0e, 0}, /* k */ - {0x0f, 0}, /* l */ - {0x10, 0}, /* m */ - {0x11, 0}, /* n */ - {0x12, 0}, /* o */ - {0x13, 0}, /* p */ - {0x14, 0}, /* q */ - {0x15, 0}, /* r */ - {0x16, 0}, /* s */ - {0x17, 0}, /* t */ - {0x18, 0}, /* u */ - {0x19, 0}, /* v */ - {0x1a, 0}, /* w */ - {0x1b, 0}, /* x */ - {0x1c, 0}, /* y */ - {0x1d, 0}, /* z */ - {0x2f, KEY_SHIFT}, /* { */ - {0x64, KEY_SHIFT}, /* | */ - {0x30, KEY_SHIFT}, /* } */ - {0x32, KEY_SHIFT}, /* ~ */ - {0,0}, /* DEL */ - - {0x3a, 0}, /* F1 */ - {0x3b, 0}, /* F2 */ - {0x3c, 0}, /* F3 */ - {0x3d, 0}, /* F4 */ - {0x3e, 0}, /* F5 */ - {0x3f, 0}, /* F6 */ - {0x40, 0}, /* F7 */ - {0x41, 0}, /* F8 */ - {0x42, 0}, /* F9 */ - {0x43, 0}, /* F10 */ - {0x44, 0}, /* F11 */ - {0x45, 0}, /* F12 */ - - {0x46, 0}, /* PRINT_SCREEN */ - {0x47, 0}, /* SCROLL_LOCK */ - {0x39, 0}, /* CAPS_LOCK */ - {0x53, 0}, /* NUM_LOCK */ - {0x49, 0}, /* INSERT */ - {0x4a, 0}, /* HOME */ - {0x4b, 0}, /* PAGE_UP */ - {0x4e, 0}, /* PAGE_DOWN */ - - {0x4f, 0}, /* RIGHT_ARROW */ - {0x50, 0}, /* LEFT_ARROW */ - {0x51, 0}, /* DOWN_ARROW */ - {0x52, 0}, /* UP_ARROW */ -}; -#endif - -#endif diff --git a/lib/ESP32_BLE_Arduino/src/HIDTypes.h b/lib/ESP32_BLE_Arduino/src/HIDTypes.h deleted file mode 100644 index 726b84be..00000000 --- a/lib/ESP32_BLE_Arduino/src/HIDTypes.h +++ /dev/null @@ -1,96 +0,0 @@ -/* Copyright (c) 2010-2011 mbed.org, MIT License -* -* 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. -*/ - -#ifndef USBCLASS_HID_TYPES -#define USBCLASS_HID_TYPES - -#include - -/* */ -#define HID_VERSION_1_11 (0x0111) - -/* HID Class */ -#define HID_CLASS (3) -#define HID_SUBCLASS_NONE (0) -#define HID_PROTOCOL_NONE (0) - -/* Descriptors */ -#define HID_DESCRIPTOR (33) -#define HID_DESCRIPTOR_LENGTH (0x09) -#define REPORT_DESCRIPTOR (34) - -/* Class requests */ -#define GET_REPORT (0x1) -#define GET_IDLE (0x2) -#define SET_REPORT (0x9) -#define SET_IDLE (0xa) - -/* HID Class Report Descriptor */ -/* Short items: size is 0, 1, 2 or 3 specifying 0, 1, 2 or 4 (four) bytes */ -/* of data as per HID Class standard */ - -/* Main items */ -#ifdef ARDUINO_ARCH_ESP32 -#define HIDINPUT(size) (0x80 | size) -#define HIDOUTPUT(size) (0x90 | size) -#else -#define INPUT(size) (0x80 | size) -#define OUTPUT(size) (0x90 | size) -#endif -#define FEATURE(size) (0xb0 | size) -#define COLLECTION(size) (0xa0 | size) -#define END_COLLECTION(size) (0xc0 | size) - -/* Global items */ -#define USAGE_PAGE(size) (0x04 | size) -#define LOGICAL_MINIMUM(size) (0x14 | size) -#define LOGICAL_MAXIMUM(size) (0x24 | size) -#define PHYSICAL_MINIMUM(size) (0x34 | size) -#define PHYSICAL_MAXIMUM(size) (0x44 | size) -#define UNIT_EXPONENT(size) (0x54 | size) -#define UNIT(size) (0x64 | size) -#define REPORT_SIZE(size) (0x74 | size) //bits -#define REPORT_ID(size) (0x84 | size) -#define REPORT_COUNT(size) (0x94 | size) //bytes -#define PUSH(size) (0xa4 | size) -#define POP(size) (0xb4 | size) - -/* Local items */ -#define USAGE(size) (0x08 | size) -#define USAGE_MINIMUM(size) (0x18 | size) -#define USAGE_MAXIMUM(size) (0x28 | size) -#define DESIGNATOR_INDEX(size) (0x38 | size) -#define DESIGNATOR_MINIMUM(size) (0x48 | size) -#define DESIGNATOR_MAXIMUM(size) (0x58 | size) -#define STRING_INDEX(size) (0x78 | size) -#define STRING_MINIMUM(size) (0x88 | size) -#define STRING_MAXIMUM(size) (0x98 | size) -#define DELIMITER(size) (0xa8 | size) - -/* HID Report */ -/* Where report IDs are used the first byte of 'data' will be the */ -/* report ID and 'length' will include this report ID byte. */ - -#define MAX_HID_REPORT_SIZE (64) - -typedef struct { - uint32_t length; - uint8_t data[MAX_HID_REPORT_SIZE]; -} HID_REPORT; - -#endif diff --git a/lib/ESPiLight/LICENSE.txt b/lib/ESPiLight/LICENSE.txt deleted file mode 100755 index 94a9ed02..00000000 --- a/lib/ESPiLight/LICENSE.txt +++ /dev/null @@ -1,674 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. diff --git a/lib/ESPiLight/Makefile b/lib/ESPiLight/Makefile deleted file mode 100755 index 99f0ccad..00000000 --- a/lib/ESPiLight/Makefile +++ /dev/null @@ -1,91 +0,0 @@ -# ESPiLight - pilight 433.92 MHz protocols library for Arduino -# Copyright (c) 2016 Puuu. All right reserved. -# -# Project home: https://github.com/puuu/espilight/ -# This library is free software; you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public -# License as published by the Free Software Foundation; either -# version 3 of the License, or (at your option) any later version. -# This library is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with library. If not, see - -SRC_DIR = pilight - -DST_DIR = src/pilight -PROTOCOL_DIR = libs/pilight/protocols/433.92 - -PROTOCOLS = $(patsubst $(SRC_DIR)/$(PROTOCOL_DIR)/%.h,%,$(sort $(wildcard $(SRC_DIR)/$(PROTOCOL_DIR)/*.h))) - -PILIGHT_FILES = libs/pilight/core/dso.h libs/pilight/core/mem.h \ - libs/pilight/core/json.h libs/pilight/core/json.c \ - libs/pilight/core/binary.h libs/pilight/core/binary.c \ - libs/pilight/protocols/protocol_header.h \ - libs/pilight/protocols/protocol_init.h -PROTOCOL_H_FILES = $(foreach protocol,$(PROTOCOLS),$(PROTOCOL_DIR)/$(protocol).h) -PROTOCOL_C_FILES = $(foreach protocol,$(PROTOCOLS),$(PROTOCOL_DIR)/$(protocol).c) -FILES = $(PILIGHT_FILES) $(PROTOCOL_H_FILES) $(PROTOCOL_C_FILES) - -DST_FILES = $(foreach file,$(FILES),$(DST_DIR)/$(file)) - -.PHONY: all clean copy update release - -all: $(SRC_DIR)/libs - $(MAKE) -e copy - -copy: $(DST_FILES) - -$(DST_DIR)/%: $(SRC_DIR)/% - @mkdir -p $(@D) - cp $< $@ - -$(DST_DIR)/libs/pilight/core/json.c: $(SRC_DIR)/libs/pilight/core/json.c - @mkdir -p $(@D) - cp $< $@ -# ESP8266 Android, sprintf not working with float. Patch: - sed 's/\(^[ \t]*\)\(sprintf(buf, "%.*f", decimals, num);\)/#ifdef ESP8266\n\1dtostrf(num, 0, decimals, buf);\n#else\n\1\2\n#endif/' -i $@ -# Arduino did not provide printf, fprintf - sed 's!#include !#include \n#include "../../../../tools/aprintf.h"!' -i $@ - -$(DST_DIR)/libs/pilight/protocols/protocol_header.h: - for protocol in $(PROTOCOLS); do\ - echo "#include \"433.92/$${protocol}.h\"" >> $@;\ - done - -$(DST_DIR)/libs/pilight/protocols/protocol_init.h: $(foreach file,$(PROTOCOL_C_FILES),$(DST_DIR)/$(file)) - for cfile in $^; do\ - grep 'void .*Init(' $$cfile | sed 's/void \(.*Init\)(.*/\1();/' >> $@;\ - done - -pilight/libs: - git submodule update --init pilight - -update: - $(MAKE) clean - git submodule update pilight - $(MAKE) copy - -release: $(SRC_DIR)/libs - git checkout release - git merge master - make update - git add src/pilight - git commit -m "integrate new pilight files" - @echo "change log:" - @git log --pretty="* %s" --no-merges HEAD...`git describe --abbrev=0 --tags` - @git submodule summary `git describe --abbrev=0 --tags` - @echo "run: git tag -a v"`grep version library.properties | sed 's/version=\(.*\)/\1/g'` - -clean: - -rm $(DST_FILES) - -stylecheck: - RESULT=0;\ - for file in src/*.h src/*.cpp src/tools/*.h src/tools/*.cpp tests/*/*.ino examples/*/*.ino; do\ - clang-format -style=google "$$file" | diff -u "$$file" - || RESULT=$$?;\ - done;\ - exit $$RESULT diff --git a/lib/ESPiLight/README.md b/lib/ESPiLight/README.md deleted file mode 100755 index 370c3fbc..00000000 --- a/lib/ESPiLight/README.md +++ /dev/null @@ -1,113 +0,0 @@ -[![Build Status](https://travis-ci.org/puuu/ESPiLight.svg?branch=master)](https://travis-ci.org/puuu/ESPiLight) - -# ESPiLight - -This Arduino library is a port of the [pilight](https://pilight.org/) -433.92MHz protocols to the Arduino platform. It was tested with a -ESP8266. The aim is to transmit, receive and parse many 433.92MHz -protocols, by providing a simple Arduino friendly API. This should -help to implement IoT bridges between the 434MHz-RF band and internet -protocols. - -By porting the C modules of the pilight protocols, allows to -participate on the excellent work of the pilight community. Thus, -supporting many protocols for rc switches and weather stations without -reimplementing them. - -A list of supported protocols can be found in the pilight manual: -https://manual.pilight.org/protocols/433.92/index.html - - -## Installation - -This library can be easily installed with the Arduino Library Manager. - - -## Usage - -Please have a look to the examples. - - -### Requirements - -This library was tested and developed for the -[ESP8266](https://github.com/esp8266/Arduino). It may not run on a -ATmega-based boards, because of memory usage. - -For transmitting and receiving you need 434MHz-RF modules. More -information can be found here: -- https://wiki.pilight.org/receivers -- https://wiki.pilight.org/senders -- https://github.com/sui77/rc-switch/wiki/List_TransmitterReceiverModules - - -## Contributing - -If you find any bug, feel free to open an issue at github. Also, pull -requests are welcome. The development takes place in the `master` -branch. The `release` is used to integrate the pilight files and for -version tagging, like necessary for the Arduino Library Manager -crawler. - -To prevent formating issues, please make sure that your code is proper -formatted. We use the `clang-format` tool with the `Google` style. -You can just format the code by calling -```console -$ clang-format -style=Google -i -``` - - -### Install from source - -If you are interested to install this library from source, you need to -integrate the pilight source files. Since Arduino build all cpp/c -files in the src directory and sub directories, only necessary files -from pilight will be integrated. This will be done with GNU make. - -On Linux you can run: -```console -$ git clone https://github.com/puuu/ESPiLight/ -$ cd ESPiLight -$ make -$ ln -s `pwd` ~/Arduino/libraries/ -``` - - -#### Update - -To update EPiLight from git run: -```console -$ git pull -$ make update -``` - - -#### New protocols - -ESPiLight only supports the 434MHz protocols supported by -[pilight](https://pilight.org/). If you are missing any protocol, -please report it directly to pilight. After the intergratrion into -pilight it can be merged into ESPILight. - -To report new protocols, please folow the -[rules](https://forum.pilight.org/showthread.php?tid=761) of the -[pilight forum](https://forum.pilight.org/). It is recommended to use -pilight directly. Alternativly, ESPiLight offers the -[`pilight_debug`](examples/pilight_debug/pilight_debug.ino) and -[`pilight_raw`](examples/pilight_raw/pilight_raw.ino) examples that -mimic tht pilight counterparts. - - -## Acknowledgement - -Big thanks goes to the pilight community, which implemented all the -434MHz protocols. If you want to integrate more protocols, please -contribute directly to [pilight](https://pilight.org/). - -[@janLo](https://github.com/janLo) [contributed](https://github.com/puuu/ESPiLight/graphs/contributors) some major cleanups and new functionalities to the library. - -## Other similar projects - -There are other, more lightweight 434Mhz implementations: -- https://github.com/sui77/rc-switch -- https://bitbucket.org/fuzzillogic/433mhzforarduino/wiki/Home diff --git a/lib/ESPiLight/examples/Receive/Receive.ino b/lib/ESPiLight/examples/Receive/Receive.ino deleted file mode 100755 index 53557722..00000000 --- a/lib/ESPiLight/examples/Receive/Receive.ino +++ /dev/null @@ -1,55 +0,0 @@ -/* - Basic ESPilight receive example - - https://github.com/puuu/espilight -*/ - -#include - -#define RECEIVER_PIN 4 // any intterupt able pin -#define TRANSMITTER_PIN 13 - -ESPiLight rf(TRANSMITTER_PIN); // use -1 to disable transmitter - -// callback function. It is called on successfully received and parsed rc signal -void rfCallback(const String &protocol, const String &message, int status, - size_t repeats, const String &deviceID) { - Serial.print("RF signal arrived ["); - Serial.print(protocol); // protocoll used to parse - Serial.print("]["); - Serial.print(deviceID); // value of id key in json message - Serial.print("] ("); - Serial.print(status); // status of message, depending on repeat, either: - // FIRST - first message of this protocoll within the - // last 0.5 s - // INVALID - message repeat is not equal to the - // previous message - // VALID - message is equal to the previous message - // KNOWN - repeat of a already valid message - Serial.print(") "); - Serial.print(message); // message in json format - Serial.println(); - - // check if message is valid and process it - if (status == VALID) { - Serial.print("Valid message: ["); - Serial.print(protocol); - Serial.print("] "); - Serial.print(message); - Serial.println(); - } -} - -void setup() { - Serial.begin(115200); - // set callback funktion - rf.setCallback(rfCallback); - // inittilize receiver - rf.initReceiver(RECEIVER_PIN); -} - -void loop() { - // process input queue and may fire calllback - rf.loop(); - delay(10); -} diff --git a/lib/ESPiLight/examples/Receive_Raw/Receive_Raw.ino b/lib/ESPiLight/examples/Receive_Raw/Receive_Raw.ino deleted file mode 100755 index 1454ea4d..00000000 --- a/lib/ESPiLight/examples/Receive_Raw/Receive_Raw.ino +++ /dev/null @@ -1,43 +0,0 @@ -/* - Basic ESPiLight receive raw (pulse train) signal example - - https://github.com/puuu/espilight -*/ - -#include - -#define RECEIVER_PIN 4 // any intterupt able pin -#define TRANSMITTER_PIN 13 - -ESPiLight rf(TRANSMITTER_PIN); // use -1 to disable transmitter - -// callback function. It is called on successfully received and parsed rc signal -void rfRawCallback(const uint16_t* codes, size_t length) { - // print pulse lengths - Serial.print("RAW signal: "); - for (unsigned int i = 0; i < length; i++) { - Serial.print(codes[i]); - Serial.print(' '); - } - Serial.println(); - - // format of pilight USB Nano - String data = rf.pulseTrainToString(codes, length); - Serial.print("string format: "); - Serial.print(data); - Serial.println(); -} - -void setup() { - Serial.begin(115200); - // set callback funktion for raw messages - rf.setPulseTrainCallBack(rfRawCallback); - // inittilize receiver - rf.initReceiver(RECEIVER_PIN); -} - -void loop() { - // process input queue and may fire calllback - rf.loop(); - delay(10); -} diff --git a/lib/ESPiLight/examples/Transmit/Transmit.ino b/lib/ESPiLight/examples/Transmit/Transmit.ino deleted file mode 100755 index 6e3e4add..00000000 --- a/lib/ESPiLight/examples/Transmit/Transmit.ino +++ /dev/null @@ -1,21 +0,0 @@ -/* - Basic ESPiLight transmit example - - https://github.com/puuu/espilight -*/ - -#include - -#define TRANSMITTER_PIN 13 - -ESPiLight rf(TRANSMITTER_PIN); - -void setup() { Serial.begin(115200); } - -// Toggle state of elro 800 switch evrey 2 s -void loop() { - rf.send("elro_800_switch", "{\"systemcode\":17,\"unitcode\":1,\"on\":1}"); - delay(2000); - rf.send("elro_800_switch", "{\"systemcode\":17,\"unitcode\":1,\"off\":1}"); - delay(2000); -} diff --git a/lib/ESPiLight/examples/Transmit_Raw/Transmit_Raw.ino b/lib/ESPiLight/examples/Transmit_Raw/Transmit_Raw.ino deleted file mode 100755 index c9064e1d..00000000 --- a/lib/ESPiLight/examples/Transmit_Raw/Transmit_Raw.ino +++ /dev/null @@ -1,32 +0,0 @@ -/* - Basic ESPiLight transmit RAW signal example - - https://github.com/puuu/espilight -*/ - -#include - -#define TRANSMITTER_PIN 13 - -ESPiLight rf(TRANSMITTER_PIN); - -void setup() { - Serial.begin(115200); - - int length = 0; - uint16_t codes[MAXPULSESTREAMLENGTH]; - - // get pulse train from string (format see: pilight USB Nano) - length = rf.stringToPulseTrain( - "c:102020202020202020220202020020202200202200202020202020220020202203;p:" - "279,2511,1395,9486@", - codes, MAXPULSESTREAMLENGTH); - - // transmit the pulse train - rf.sendPulseTrain(codes, length); -} - -// Toggle state of elro 800 switch evrey 2 s -void loop() { - // stop -} diff --git a/lib/ESPiLight/examples/pilight_debug/pilight_debug.ino b/lib/ESPiLight/examples/pilight_debug/pilight_debug.ino deleted file mode 100755 index 1f5ce726..00000000 --- a/lib/ESPiLight/examples/pilight_debug/pilight_debug.ino +++ /dev/null @@ -1,81 +0,0 @@ -/* - Basic ESPiLight pilight_debug example - - This example mimic the output of the piligh_debug tool. - - https://github.com/puuu/espilight -*/ - -#include - -#define PULSE_DIV 34 - -#define RECEIVER_PIN 4 // any intterupt able pin -#define TRANSMITTER_PIN 13 - -ESPiLight rf(TRANSMITTER_PIN); // use -1 to disable transmitter - -unsigned int normalize(unsigned int i, unsigned int pulselen) { - double x; - x = (double)i / pulselen; - - return (unsigned int)(round(x)); -} - -// callback function. It is called on successfully received and parsed rc signal -void rfRawCallback(const uint16_t* pulses, size_t length) { - uint16_t pulse; - uint16_t pulselen = pulses[length - 1] / PULSE_DIV; - if (pulselen > 25) { - for (unsigned int i = 3; i < length; i++) { - if ((pulses[i] / pulselen) >= 2) { - pulse = pulses[i]; - break; - } - } - if (normalize(pulse, pulselen) > 0 && length > 25) { - /* Print everything */ - Serial.println("--[RESULTS]--"); - Serial.println(); - Serial.print("time:\t\t"); - Serial.print(millis()); - Serial.println(" ms"); - Serial.println("hardware:\tESPiLight"); - Serial.print("pulse:\t\t"); - Serial.println(normalize(pulse, pulselen)); - Serial.print("rawlen:\t\t"); - Serial.println(length); - Serial.printf("pulselen:\t"); - Serial.println(pulselen); - Serial.println(); - Serial.println("Raw code:"); - for (unsigned int i = 0; i < length; i++) { - Serial.print(pulses[i]); - Serial.print(" "); - } - Serial.println(); - } - } -} - -void setup() { - Serial.begin(115200); - // set callback funktion for raw messages - rf.setPulseTrainCallBack(rfRawCallback); - // inittilize receiver - rf.initReceiver(RECEIVER_PIN); - - Serial.println( - "Press and hold one of the buttons on your remote or wait until"); - Serial.println("another device such as a weather station has sent new codes"); - Serial.println( - "The debugger will automatically reset itself after one second of"); - Serial.println( - "failed leads. It will keep running until you explicitly stop it."); -} - -void loop() { - // process input queue and may fire calllback - rf.loop(); - delay(10); -} diff --git a/lib/ESPiLight/examples/pilight_raw/pilight_raw.ino b/lib/ESPiLight/examples/pilight_raw/pilight_raw.ino deleted file mode 100755 index 69f20098..00000000 --- a/lib/ESPiLight/examples/pilight_raw/pilight_raw.ino +++ /dev/null @@ -1,41 +0,0 @@ -/* - Basic ESPiLight pilight_raw example - - This example mimic the output of the piligh_raw tool. - - https://github.com/puuu/espilight -*/ - -#include - -#define RECEIVER_PIN 4 // any intterupt able pin -#define TRANSMITTER_PIN 13 - -ESPiLight rf(TRANSMITTER_PIN); // use -1 to disable transmitter - -// callback function. It is called on successfully received and parsed rc signal -void rfRawCallback(const uint16_t* pulses, size_t length) { - Serial.print("ESPiLight:"); - for (unsigned int i = 0; i < length; i++) { - Serial.print(" "); - Serial.print(pulses[i]); - if (pulses[i] > 5100) { - Serial.printf(" -# "); - Serial.println(i); - } - } -} - -void setup() { - Serial.begin(115200); - // set callback funktion for raw messages - rf.setPulseTrainCallBack(rfRawCallback); - // inittilize receiver - rf.initReceiver(RECEIVER_PIN); -} - -void loop() { - // process input queue and may fire calllback - rf.loop(); - delay(10); -} diff --git a/lib/ESPiLight/keywords.txt b/lib/ESPiLight/keywords.txt deleted file mode 100755 index 9d3bece2..00000000 --- a/lib/ESPiLight/keywords.txt +++ /dev/null @@ -1,44 +0,0 @@ -####################################### -# Syntax Coloring Map For ESPiLight -####################################### - -####################################### -# Datatypes (KEYWORD1) -####################################### - -ESPiLight KEYWORD1 - -####################################### -# Methods and Functions (KEYWORD2) -####################################### - -send KEYWORD2 -loop KEYWORD2 - -initReceiver KEYWORD2 -setCallback KEYWORD2 -setPulseTrainCallBack KEYWORD2 -enableReceiver KEYWORD2 -disableReceiver KEYWORD2 - -pulseTrainToString KEYWORD2 -stringToPulseTrain KEYWORD2 -createPulseTrain KEYWORD2 -sendPulseTrain KEYWORD2 -parsePulseTrain KEYWORD2 -receivePulseTrain KEYWORD2 - -####################################### -# Instances (KEYWORD2) -####################################### - -####################################### -# Constants (LITERAL1) -####################################### - -MAXPULSESTREAMLENGTH LITERAL1 - -FIRST LITERAL1 -INVALID LITERAL1 -VALID LITERAL1 -KNOWN LITERAL1 diff --git a/lib/ESPiLight/library.json b/lib/ESPiLight/library.json deleted file mode 100755 index 8e44d450..00000000 --- a/lib/ESPiLight/library.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "name": "ESPiLight", - "keywords": "pilight, 433MHz, 434MHz, rf", - "description": "pilight 433.92 MHz protocols library for Arduino. With this port of pilight 433.92 MHz protocols, you can transmit, receive and parse all 434 MHz protocols (e.g., rc switches or weather stations) supported by pilight. This should help to implement IoT bridges between the 434MHz-RF band and internet protocols. It is developed and tested on ESP8266.", - "repository": - { - "type": "git", - "url": "https://github.com/puuu/ESPiLight.git" - }, - "version": "0.16.0", - "license": "GPL-3.0", - "frameworks": "arduino", - "platforms": - [ - "espressif8266", - "espressif32" - ] -} diff --git a/lib/ESPiLight/library.properties b/lib/ESPiLight/library.properties deleted file mode 100755 index a8a46e21..00000000 --- a/lib/ESPiLight/library.properties +++ /dev/null @@ -1,9 +0,0 @@ -name=ESPiLight -version=0.16.0 -author=Puuu -maintainer=Puuu -sentence=pilight 433.92 MHz protocols library for Arduino -paragraph=With this port of pilight 433.92 MHz protocols, you can transmit, receive and parse all 434 MHz protocols (e.g., rc switches or weather stations) supported by pilight. This should help to implement IoT bridges between the 434MHz-RF band and internet protocols. It is developed and tested on ESP8266. -category=Signal Input/Output -url=https://github.com/puuu/espilight -architectures=esp8266,esp32 diff --git a/lib/ESPiLight/src/ESPiLight.cpp b/lib/ESPiLight/src/ESPiLight.cpp deleted file mode 100755 index 2859a0e4..00000000 --- a/lib/ESPiLight/src/ESPiLight.cpp +++ /dev/null @@ -1,595 +0,0 @@ -/* - ESPiLight - pilight 433.92 MHz protocols library for Arduino - Copyright (c) 2016 Puuu. All right reserved. - - Project home: https://github.com/puuu/espilight/ - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 3 of the License, or (at your option) any later version. - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU General Public License - along with library. If not, see -*/ - -#include -#include "tools/aprintf.h" - -// ESP32 doesn't define ICACHE_RAM_ATTR -#ifndef ICACHE_RAM_ATTR -#define ICACHE_RAM_ATTR IRAM_ATTR -#endif - -#ifdef DEBUG -#define Debug(x) Serial.print(x) -#define DebugLn(x) Serial.println(x) -#else -#define Debug(x) -#define DebugLn(x) -#endif - -extern "C" { -#include "pilight/libs/pilight/protocols/protocol.h" -} -static protocols_t *used_protocols = nullptr; - -volatile PulseTrain_t ESPiLight::_pulseTrains[RECEIVER_BUFFER_SIZE]; -bool ESPiLight::_enabledReceiver; -volatile uint8_t ESPiLight::_actualPulseTrain = 0; -uint8_t ESPiLight::_avaiablePulseTrain = 0; -volatile unsigned long ESPiLight::_lastChange = - 0; // Timestamp of previous edge -volatile uint8_t ESPiLight::_nrpulses = 0; -int16_t ESPiLight::_interrupt = NOT_AN_INTERRUPT; - -uint8_t ESPiLight::minrawlen = 5; -uint8_t ESPiLight::maxrawlen = MAXPULSESTREAMLENGTH; -uint16_t ESPiLight::mingaplen = 5100; -uint16_t ESPiLight::maxgaplen = 10000; - -static void fire_callback(protocol_t *protocol, ESPiLightCallBack callback); - -static protocols_t *get_protocols() { - if (pilight_protocols == nullptr) { - ESPiLight::setErrorOutput(Serial); - protocol_init(); - } - return pilight_protocols; -} - -static protocols_t *get_used_protocols() { - if (used_protocols == nullptr) { - used_protocols = get_protocols(); - } - return used_protocols; -} - -static protocols_t *find_protocol_node(const char *name) { - protocols_t *pnode = get_protocols(); - while (pnode != nullptr) { - if (strcmp(name, pnode->listener->id) == 0) { - return pnode; - } - pnode = pnode->next; - } - return nullptr; -} - -static protocol_t *find_protocol(const char *name) { - protocols_t *pnode = find_protocol_node(name); - if (pnode != nullptr) { - return pnode->listener; - } - return nullptr; -} - -static int create_pulse_train(uint16_t *pulses, protocol_t *protocol, - const String &content) { - Debug("piLightCreatePulseTrain: "); - - if (!json_validate(content.c_str())) { - Debug("invalid json: "); - DebugLn(content); - return ESPiLight::ERROR_INVALID_JSON; - } - -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wtype-limits" - if ((protocol != nullptr) && (protocol->createCode != nullptr) && - (protocol->maxrawlen <= MAXPULSESTREAMLENGTH)) { -#pragma GCC diagnostic pop - Debug("protocol: "); - Debug(protocol->id); - - protocol->rawlen = 0; - protocol->raw = pulses; - JsonNode *message = json_decode(content.c_str()); - int return_value = protocol->createCode(message); - json_delete(message); - // delete message created by createCode() - json_delete(protocol->message); - protocol->message = nullptr; - - if (return_value == EXIT_SUCCESS) { - DebugLn(" create Code succeded."); - return protocol->rawlen; - } else { - DebugLn(" create Code failed."); - return ESPiLight::ERROR_INVALID_PILIGHT_MSG; - } - } - return ESPiLight::ERROR_UNAVAILABLE_PROTOCOL; -} - -void ESPiLight::initReceiver(byte inputPin) { - int16_t interrupt = digitalPinToInterrupt(inputPin); - if (_interrupt == interrupt) { - return; - } - if (_interrupt >= 0) { - detachInterrupt((uint8_t)_interrupt); - } - _interrupt = interrupt; - - resetReceiver(); - enableReceiver(); - - if (interrupt >= 0) { - attachInterrupt((uint8_t)interrupt, interruptHandler, CHANGE); - } -} - -uint8_t ESPiLight::receivePulseTrain(uint16_t *pulses) { - uint8_t length = nextPulseTrainLength(); - - if (length > 0) { - volatile PulseTrain_t &pulseTrain = _pulseTrains[_avaiablePulseTrain]; - _avaiablePulseTrain = (_avaiablePulseTrain + 1) % RECEIVER_BUFFER_SIZE; - for (uint8_t i = 0; i < length; i++) { - pulses[i] = pulseTrain.pulses[i]; - } - pulseTrain.length = 0; - } - return length; -} - -uint8_t ESPiLight::nextPulseTrainLength() { - return _pulseTrains[_avaiablePulseTrain].length; -} - -void ICACHE_RAM_ATTR ESPiLight::interruptHandler() { - if (!_enabledReceiver) { - return; - } - - unsigned long now = micros(); - unsigned int duration = 0; - - volatile PulseTrain_t &pulseTrain = _pulseTrains[_actualPulseTrain]; - volatile uint16_t *codes = pulseTrain.pulses; - - if (pulseTrain.length == 0) { - duration = now - _lastChange; - /* We first do some filtering (same as pilight BPF) */ - if (duration > MIN_PULSELENGTH) { - if (duration < MAX_PULSELENGTH) { - /* All codes are buffered */ - codes[_nrpulses] = (uint16_t)duration; - _nrpulses = (uint8_t)((_nrpulses + 1) % MAXPULSESTREAMLENGTH); - /* Let's match footers */ - if (duration > mingaplen) { - // Debug('g'); - /* Only match minimal length pulse streams */ - if (_nrpulses >= minrawlen && _nrpulses <= maxrawlen) { - // Debug(_nrpulses); - // Debug('l'); - pulseTrain.length = _nrpulses; - _actualPulseTrain = (_actualPulseTrain + 1) % RECEIVER_BUFFER_SIZE; - } - _nrpulses = 0; - } - } - _lastChange = now; - } - } else { - Debug("_!_"); - } -} - -void ESPiLight::resetReceiver() { - for (unsigned int i = 0; i < RECEIVER_BUFFER_SIZE; i++) { - _pulseTrains[i].length = 0; - } - _avaiablePulseTrain = 0; - _actualPulseTrain = 0; - _nrpulses = 0; -} - -void ESPiLight::enableReceiver() { _enabledReceiver = true; } - -void ESPiLight::disableReceiver() { _enabledReceiver = false; } - -void ESPiLight::loop() { - int length = 0; - uint16_t pulses[MAXPULSESTREAMLENGTH]; - - length = receivePulseTrain(pulses); - - if (length > 0) { - /* - Debug("RAW ("); - Debug(length); - Debug("): "); - for(int i=0;i= 0) { - pinMode((uint8_t)_outputPin, OUTPUT); - digitalWrite((uint8_t)_outputPin, LOW); - } - - get_protocols(); -} - -void ESPiLight::setCallback(ESPiLightCallBack callback) { - _callback = callback; -} - -void ESPiLight::setPulseTrainCallBack(PulseTrainCallBack rawCallback) { - _rawCallback = rawCallback; -} - -void ESPiLight::sendPulseTrain(const uint16_t *pulses, size_t length, - size_t repeats) { - if (_outputPin >= 0) { - bool receiverState = _enabledReceiver; - _enabledReceiver = (_echoEnabled && receiverState); - for (unsigned int r = 0; r < repeats; r++) { - for (unsigned int i = 0; i < length; i += 2) { - digitalWrite((uint8_t)_outputPin, HIGH); - delayMicroseconds(pulses[i]); - digitalWrite((uint8_t)_outputPin, LOW); - if (i + 1 < length) { - delayMicroseconds(pulses[i + 1]); - } - } - } - digitalWrite((uint8_t)_outputPin, LOW); - _enabledReceiver = receiverState; - } -} - -int ESPiLight::send(const String &protocol, const String &json, - size_t repeats) { - if (_outputPin < 0) { - DebugLn("No output pin set, cannot send"); - return ERROR_NO_OUTPUT_PIN; - } - int length = 0; - uint16_t pulses[MAXPULSESTREAMLENGTH]; - - protocol_t *protocol_listener = find_protocol(protocol.c_str()); - length = create_pulse_train(pulses, protocol_listener, json); - if (length > 0) { - /* - DebugLn(); - Debug("send: "); - Debug(length); - Debug(" pulses ("); - Debug(protocol); - Debug(", "); - Debug(content); - DebugLn(")"); - */ - if (repeats == 0) { - repeats = protocol_listener->txrpt; - } - sendPulseTrain(pulses, (unsigned)length, repeats); - } - return length; -} - -int ESPiLight::createPulseTrain(uint16_t *pulses, const String &protocol_id, - const String &content) { - protocol_t *protocol = find_protocol(protocol_id.c_str()); - return create_pulse_train(pulses, protocol, content); -} - -size_t ESPiLight::parsePulseTrain(uint16_t *pulses, uint8_t length) { - size_t matches = 0; - protocol_t *protocol = nullptr; - protocols_t *pnode = get_used_protocols(); - - // DebugLn("piLightParsePulseTrain start"); - while ((pnode != nullptr) && (_callback != nullptr)) { - protocol = pnode->listener; - - if (protocol->parseCode != nullptr && protocol->validate != nullptr) { - protocol->raw = pulses; - protocol->rawlen = length; - - if (protocol->validate() == 0) { - Debug("pulses: "); - Debug(length); - Debug(" possible protocol: "); - DebugLn(protocol->id); - - if (protocol->first > 0) { - protocol->first = protocol->second; - } - protocol->second = micros(); - if (protocol->first == 0) { - protocol->first = protocol->second; - } - - /* Reset # of repeats after a certain delay */ - if ((protocol->second - protocol->first) > 500000) { - protocol->repeats = 0; - } - - protocol->message = nullptr; - protocol->parseCode(); - if (protocol->message != nullptr) { - matches++; - protocol->repeats++; - - fire_callback(protocol, _callback); - - json_delete(protocol->message); - protocol->message = nullptr; - } - } - } - pnode = pnode->next; - } - if (_rawCallback != nullptr) { - (_rawCallback)(pulses, length); - } - - // Debug("piLightParsePulseTrain end. matches: "); - // DebugLn(matches); - return matches; -} - -static void fire_callback(protocol_t *protocol, ESPiLightCallBack callback) { - PilightRepeatStatus_t status = FIRST; - char *content = json_encode(protocol->message); - String deviceId = ""; - double itmp; - char *stmp; - - if ((protocol->repeats <= 1) || (protocol->old_content == nullptr)) { - status = FIRST; - json_free(protocol->old_content); - protocol->old_content = content; - } else if (!(protocol->repeats & 0x80)) { - if (strcmp(content, protocol->old_content) == 0) { - protocol->repeats |= 0x80; - status = VALID; - } else { - status = INVALID; - } - json_free(protocol->old_content); - protocol->old_content = content; - } else { - status = KNOWN; - json_free(content); - } - if (json_find_number(protocol->message, "id", &itmp) == 0) { - deviceId = String((int)round(itmp)); - } else if (json_find_string(protocol->message, "id", &stmp) == 0) { - deviceId = String(stmp); - }; - (callback)(String(protocol->id), String(protocol->old_content), status, - protocol->repeats & 0x7F, deviceId); -} - -String ESPiLight::pulseTrainToString(const uint16_t *codes, size_t length) { - bool match = false; - int diff = 0; - - uint8_t nrpulses = 0; // number of pulse types - uint16_t plstypes[MAX_PULSE_TYPES] = {}; - - String data(""); - data.reserve(6 + length); - data += "c:"; - for (unsigned int i = 0; i < length; i++) { - match = false; - for (uint8_t j = 0; j < MAX_PULSE_TYPES; j++) { - // We device these numbers by 10 to normalize them a bit - diff = (plstypes[j] / 50) - (codes[i] / 50); - if ((diff >= -2) && (diff <= 2)) { - // Write numbers - data += (char)('0' + ((char)j)); - match = true; - break; - } - } - if (!match) { - plstypes[nrpulses++] = codes[i]; - data += (char)('0' + ((char)(nrpulses - 1))); - if (nrpulses >= MAX_PULSE_TYPES) { - DebugLn("too many pulse types"); - return String(""); - } - } - } - data += ";p:"; - for (uint8_t i = 0; i < nrpulses; i++) { - data += plstypes[i]; - if (i + 1 < nrpulses) { - data += ','; - } - } - data += '@'; - return data; -} - -int ESPiLight::stringToPulseTrain(const String &data, uint16_t *codes, - size_t maxlength) { - unsigned int length = 0; // length of pulse train - unsigned int nrpulses = 0; // number of pulse types - uint16_t plstypes[MAX_PULSE_TYPES] = {}; - - // validate data string - int scode = data.indexOf('c') + 2; - if (scode < 0 || (unsigned)scode > data.length()) { - DebugLn("'c' not found in data string, or has no data"); - return ERROR_INVALID_PULSETRAIN_MSG_C; - } - int spulse = data.indexOf('p') + 2; - if (spulse < 0 || (unsigned)spulse > data.length()) { - DebugLn("'p' not found in data string, or has no data"); - return ERROR_INVALID_PULSETRAIN_MSG_P; - } - // parsing pulse types - unsigned int start = (unsigned)spulse; - int end = data.indexOf(',', start); - while (end > 0) { - plstypes[nrpulses++] = - (uint16_t)data.substring(start, (unsigned)end).toInt(); - start = (unsigned)end + 1; - end = data.indexOf(',', start); - } - end = data.indexOf(';', start); - if (end < 0) { - end = data.indexOf('@', start); - } - if (end < 0) { - DebugLn("';' or '@' not found in data string"); - return ERROR_INVALID_PULSETRAIN_MSG_END; - } - plstypes[nrpulses++] = (uint16_t)data.substring(start, (unsigned)end).toInt(); - // parsing pulses - int pulse_index = 0; - for (unsigned int i = (unsigned)scode; i < data.length(); i++) { - if ((data[i] == ';') || (data[i] == '@')) break; - if (i >= maxlength) break; - pulse_index = data[i] - '0'; - if ((pulse_index < 0) || ((unsigned)pulse_index >= nrpulses)) { - DebugLn("Pulse type not defined"); - return ERROR_INVALID_PULSETRAIN_MSG_TYPE; - } - codes[length++] = plstypes[pulse_index]; - } - return length; -} - -void ESPiLight::limitProtocols(const String &protos) { - if (!json_validate(protos.c_str())) { - DebugLn("Protocol limit argument is not a valid json message!"); - return; - } - JsonNode *message = json_decode(protos.c_str()); - - if (message->tag != JSON_ARRAY) { - DebugLn("Protocol limit argument is not a json array!"); - json_delete(message); - return; - } - - if (get_used_protocols() != get_protocols()) { - protocols_t *pnode = get_used_protocols(); - while (pnode != nullptr) { - protocols_t *tmp = pnode; - pnode = pnode->next; - delete tmp; - } - } - - used_protocols = nullptr; - JsonNode *curr = message->children.head; - unsigned int proto_count = 0; - - while (curr != nullptr) { - if (curr->tag != JSON_STRING) { - DebugLn("Element is not a String"); - curr = curr->next; - continue; - } - - protocols_t *templ = find_protocol_node(curr->string_); - if (templ == nullptr) { - Debug("Protocol not found: "); - DebugLn(curr->string_); - curr = curr->next; - continue; - } - - protocols_t *new_node = new protocols_t; - new_node->listener = templ->listener; - new_node->next = used_protocols; - used_protocols = new_node; - - Debug("activated protocol "); - DebugLn(templ->listener->id); - proto_count++; - - if (curr == message->children.tail) { - break; - } - curr = curr->next; - } - - json_delete(message); -} - -static String protocols_to_array(protocols_t *pnode) { - protocols_t *tmp = pnode; - size_t needed_len = 2; // [] - while (tmp != nullptr) { - needed_len += strlen(tmp->listener->id) + 3; // "xx", - tmp = tmp->next; - } - - String ret; - ret.reserve(needed_len); - - ret += '['; - - bool first = true; - while (pnode != nullptr) { - if (first) { - first = false; - } else { - ret += ","; - } - ret += '"'; - ret += pnode->listener->id; - ret += '"'; - pnode = pnode->next; - } - ret += "]"; - - return ret; -} - -String ESPiLight::availableProtocols() { - return protocols_to_array(get_protocols()); -} - -String ESPiLight::enabledProtocols() { - return protocols_to_array(get_used_protocols()); -} - -void ESPiLight::setEchoEnabled(bool enabled) { _echoEnabled = enabled; } - -void ESPiLight::setErrorOutput(Print &output) { set_aprintf_output(&output); } diff --git a/lib/ESPiLight/src/ESPiLight.h b/lib/ESPiLight/src/ESPiLight.h deleted file mode 100755 index 579d2c23..00000000 --- a/lib/ESPiLight/src/ESPiLight.h +++ /dev/null @@ -1,200 +0,0 @@ -/* - ESPiLight - pilight 433.92 MHz protocols library for Arduino - Copyright (c) 2016 Puuu. All right reserved. - - Project home: https://github.com/puuu/espilight/ - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 3 of the License, or (at your option) any later version. - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU General Public License - along with library. If not, see -*/ - -#ifndef ESPILIGHT_H -#define ESPILIGHT_H - -#include -#include - -#ifndef RECEIVER_BUFFER_SIZE -#define RECEIVER_BUFFER_SIZE 10 -#endif - -#define MIN_PULSELENGTH 80 -#define MAX_PULSELENGTH 16000 -#ifndef MAXPULSESTREAMLENGTH -#define MAXPULSESTREAMLENGTH 255 -#endif - -#define MAX_PULSE_TYPES 16 - -enum PilightRepeatStatus_t { FIRST, INVALID, VALID, KNOWN }; - -typedef struct PulseTrain_t { - uint16_t pulses[MAXPULSESTREAMLENGTH]; - uint8_t length; -} PulseTrain_t; - -typedef std::function - ESPiLightCallBack; -typedef std::function - PulseTrainCallBack; - -class ESPiLight { - public: - /** - * Constructor. - */ - ESPiLight(int8_t outputPin); - - /** - * Transmit pulse train - */ - void sendPulseTrain(const uint16_t *pulses, size_t length, - size_t repeats = 10); - - /** - * Transmit Pilight json message - * repeats of 0 means repeats as defined in protocol. - */ - int send(const String &protocol, const String &json, size_t repeats = 0); - - /** - * Parse pulse train and fire callback - */ - size_t parsePulseTrain(uint16_t *pulses, uint8_t length); - - /** - * Process receiver queue and fire callback - */ - void loop(); - - void setCallback(ESPiLightCallBack callback); - void setPulseTrainCallBack(PulseTrainCallBack rawCallback); - - /** - * If set to true, the receiver will temporarely be disabled when sending. - */ - void setEchoEnabled(bool enabled); - - /** - * Initialise receiver - */ - static void initReceiver(byte inputPin); - - /** - * Get last received PulseTrain. - * Returns: length of PulseTrain or 0 if not avaiable - */ - static uint8_t receivePulseTrain(uint16_t *pulses); - - /** - * Check if new PulseTrain avaiable. - * Returns: 0 if no new PulseTrain avaiable - */ - static uint8_t nextPulseTrainLength(); - - /** - * Enable Receiver. No need to call enableReceiver() after initReceiver(). - */ - static void enableReceiver(); - - /** - * Disable decoding. You can re-enable decoding by calling enableReceiver(); - */ - static void disableReceiver(); - - /** - * interruptHandler is called on every change in the input - * signal. If RcPilight::initReceiver is called with interrupt <0, - * you have to call interruptHandler() yourself. (Or use - * InterruptChain) - */ - static void interruptHandler(); - - /** - * Limit the available protocols. - * - * This gets a json array of the protocol names that should be activated. - * If the array is empty, the filter gets reset. - */ - static void limitProtocols(const String &protos); - - /** - * Return a json array containing all the available protocols. - */ - static String availableProtocols(); - - /** - * Return an json array containing all the currently enabled protocols - */ - static String enabledProtocols(); - - /** - * Set pilight error output Print class (default is Serial) - */ - static void setErrorOutput(Print &output); - - static uint8_t minrawlen; - static uint8_t maxrawlen; - static uint16_t mingaplen; - static uint16_t maxgaplen; - - static String pulseTrainToString(const uint16_t *pulses, size_t length); - static int stringToPulseTrain(const String &data, uint16_t *pulses, - size_t maxlength); - - static int createPulseTrain(uint16_t *pulses, const String &protocol_id, - const String &json); - - /** - * Error return codes for send() and createPulseTrain() - */ - static const int ERROR_UNAVAILABLE_PROTOCOL = 0; - static const int ERROR_INVALID_PILIGHT_MSG = -1; - static const int ERROR_INVALID_JSON = -2; - static const int ERROR_NO_OUTPUT_PIN = -3; - - /** - * Error return codes for stringToPulseTrain() - */ - static const int ERROR_INVALID_PULSETRAIN_MSG_C = -1; - static const int ERROR_INVALID_PULSETRAIN_MSG_P = -2; - static const int ERROR_INVALID_PULSETRAIN_MSG_END = -3; - static const int ERROR_INVALID_PULSETRAIN_MSG_TYPE = -4; - - private: - ESPiLightCallBack _callback; - PulseTrainCallBack _rawCallback; - int8_t _outputPin; - bool _echoEnabled; - - /** - * Quasi-reset. Called when the current edge is too long or short. - * reset "promotes" the current edge as being the first edge of a new - * sequence. - */ - static void resetReceiver(); - - /** - * Internal functions - */ - static bool _enabledReceiver; // If true, monitoring and decoding is - // enabled. If false, interruptHandler will - // return immediately. - static volatile PulseTrain_t _pulseTrains[]; - static volatile uint8_t _actualPulseTrain; - static uint8_t _avaiablePulseTrain; - static volatile unsigned long _lastChange; // Timestamp of previous edge - static volatile uint8_t _nrpulses; - static int16_t _interrupt; -}; - -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/core/binary.c b/lib/ESPiLight/src/pilight/libs/pilight/core/binary.c deleted file mode 100644 index ca8affee..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/core/binary.c +++ /dev/null @@ -1,119 +0,0 @@ -/* - Copyright (C) 2013 - 2016 CurlyMo - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. -*/ - -#include -#include - -#include "binary.h" - -/* - * Macros to help convertion of a value from and to bits. - * The value-variable passed to VALUE_TO_BITS_MSB_FIRST() - * and VALUE_TO_BITS_LSB_FIRST() MUST be an unsigned type! - * Macros have side effects to almost all variables passed! - */ - -#define BITS_LSB_FIRST_TO_VALUE(bits, s, e, result) \ - unsigned long long mask = 1; \ - result = 0; \ - for(; s<=e; mask <<= 1) \ - if(bits[s++] != 0) \ - result |= mask - -#define BITS_MSB_FIRST_TO_VALUE(bits, s, e, result) \ - unsigned long long mask = 1; \ - result = 0; \ - e++; \ - for(; e > 0 && s>= 1); \ - int *start = bits; \ - do *--start = value & 1; while (value >>= 1); \ - length = bits - start - - -#define VALUE_TO_BITS_LSB_FIRST(value, bits, length) \ - int *start = bits; \ - do *bits++ = value & 1; while (value >>= 1); \ - length = bits - start - -/* - * Invocation of above macros for various types: - * Again: - * The value-variable passed to VALUE_TO_BITS_MSB_FIRST() - * and VALUE_TO_BITS_LSB_FIRST() MUST be an unsigned type! - */ -int binToDecRev(const int *binary, int s, int e) { // 0<=s<=e, binary[s(msb) .. e(lsb)] - int result; - BITS_MSB_FIRST_TO_VALUE(binary, s, e, result); - return result; -} - -int binToDec(const int *binary, int s, int e) { // 0<=s<=e, binary[s(lsb) .. e(msb)] - int result; - BITS_LSB_FIRST_TO_VALUE(binary, s, e, result); - return result; -} - -int decToBin(int dec, int *binary) { // stores dec as binary[msb .. lsb] and return index of lsb - unsigned int n = (unsigned int) dec; - int len; - VALUE_TO_BITS_MSB_FIRST(n, binary, len); - return len - 1; // return index, not count. -} - -int decToBinRev(int dec, int *binary) { // stores dec as binary[lsb .. msb] and return index of msb - unsigned int n = (unsigned int) dec; - int len; - VALUE_TO_BITS_LSB_FIRST(n, binary, len); - return len - 1; // return index, not count. -} - -unsigned long long binToDecRevUl(const int *binary, unsigned int s, unsigned int e) { - unsigned long long result = 0; - BITS_MSB_FIRST_TO_VALUE(binary, s, e, result); - return result; -} - -unsigned long long binToDecUl(const int *binary, unsigned int s, unsigned int e) { - unsigned long long result; - BITS_LSB_FIRST_TO_VALUE(binary, s, e, result); - return result; -} - -int decToBinUl(unsigned long long n, int *binary) { - int len; - VALUE_TO_BITS_MSB_FIRST(n, binary, len); - return len - 1; // return index, not count. -} - -int decToBinRevUl(unsigned long long n, int *binary) { - int len; - VALUE_TO_BITS_LSB_FIRST(n, binary, len); - return len - 1; // return index, not count. -} - -int binToSignedRev(const int *binary, int s, int e) { // 0<=s<=e, binary[s(msb) .. e(lsb)] - int result = binToDecRev(binary, s, e); - if (binary[s]) { - result -= 1<<(e-s+1); - } - return result; -} - -int binToSigned(const int *binary, int s, int e) { // 0<=s<=e, binary[s(lsb) .. e(msb)] - int result = binToDec(binary, s, e); - if (binary[e]) { - result -= 1<<(e-s+1); - } - return result; -} \ No newline at end of file diff --git a/lib/ESPiLight/src/pilight/libs/pilight/core/binary.h b/lib/ESPiLight/src/pilight/libs/pilight/core/binary.h deleted file mode 100644 index 64af2baf..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/core/binary.h +++ /dev/null @@ -1,91 +0,0 @@ -/* - Copyright (C) 2013 - 2014 CurlyMo - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#ifndef _BINARY_H_ -#define _BINARY_H_ - -/* - * Convert "bits" to the corresponding integer value. - * The difference between binToDecRev[Ul]() and binToDec[Ul]() is where the most and where the least - * significant bit is located (at index position s or e). - * @param binary The bits to convert, each represented by an int in a buffer (non-zero = "1"). - * @param s, e Start+End index in the buffer of "bits". 0<=s<=e. e-s < sizeof(int)*8 - * @return int The converted value. - */ -int binToDecRev(const int *binary, int s, int e); // 0<=s<=e, binary[s(msb) .. e(lsb)] -int binToDec(const int *binary, int s, int e); // 0<=s<=e, binary[s(lsb) .. e(msb)] - -/* - * Convert an integer value to its bits, stored in a buffer of ints. - * The difference of decToBinRev() and decToBin() is if Most or Least Significant bit is generated first. - * IMPORTANT: binToDec() devToBin() use the "Rev"/"non-Rev" in opposit meaning: A buffer generated - * using the "Rev" function must be read by the "non-Rev" function to produce the original value. :-( - * @param dec The number to convert. - * @param binary The buffer of int where to store the "bits" (0 and 1). - * @return int The index of the last bit generated (0 if one bit was generated). - */ -int decToBinRev(int dec, int *binary); // stores dec as binary[lsb .. msb] and return index of msb -int decToBin(int dec, int *binary); // stores dec as binary[msb .. lsb] and return index of lsb - -/* - * Dito for unsigned long long values. - */ -unsigned long long binToDecRevUl(const int *binary, unsigned int s, unsigned int e); -unsigned long long binToDecUl(const int *binary, unsigned int s, unsigned int e); -int decToBinUl(unsigned long long n, int *binary); -int decToBinRevUl(unsigned long long n, int *binary); - -/* - * Convert "bits" to the corresponding signed integer value. - * The difference between binToSignedRev() and binToSigned() is where the most and where the least - * significant bit is located (at index position s or e). - * @param binary The bits to convert, each represented by an int in a buffer (non-zero = "1"). - * @param s, e Start+End index in the buffer of "bits". 0<=s<=e. e-s < sizeof(int)*8 - * @return signed int The converted value. - * - * Examples: - * binToSignedRev((int[]){0,1,1,1, 1,1,1,1}, 0, 7) == 127 - * binToSignedRev((int[]){0,1,1,1, 1,1,1,0}, 0, 7) == 126 - * binToSignedRev((int[]){0,0,0,0, 0,0,1,0}, 0, 7) == 2 - * binToSignedRev((int[]){0,0,0,0, 0,0,0,1}, 0, 7) == 1 - * binToSignedRev((int[]){0,0,0,0, 0,0,0,0}, 0, 7) == 0 - * binToSignedRev((int[]){1,1,1,1, 1,1,1,1}, 0, 7) == -1 - * binToSignedRev((int[]){1,1,1,1, 1,1,1,0}, 0, 7) == -2 - * binToSignedRev((int[]){1,0,0,0, 0,0,1,0}, 0, 7) == -126 - * binToSignedRev((int[]){1,0,0,0, 0,0,0,1}, 0, 7) == -127 - * binToSignedRev((int[]){1,0,0,0, 0,0,0,0}, 0, 7) == -128 - * binToSignedRev((int[]){1,0, 0,1,1,1, 0,0}, 2, 5) == 7 - * binToSignedRev((int[]){1,0, 1,1,1,0, 0,0}, 2, 5) == -2 - * - * binToSigned((int[]){1,1,1,1, 1,1,1,0}, 0, 7) == 127 - * binToSigned((int[]){0,1,1,1, 1,1,1,0}, 0, 7) == 126 - * binToSigned((int[]){0,1,0,0, 0,0,0,0}, 0, 7) == 2 - * binToSigned((int[]){1,0,0,0, 0,0,0,0}, 0, 7) == 1 - * binToSigned((int[]){0,0,0,0, 0,0,0,0}, 0, 7) == 0 - * binToSigned((int[]){1,1,1,1, 1,1,1,1}, 0, 7) == -1 - * binToSigned((int[]){0,1,1,1, 1,1,1,1}, 0, 7) == -2 - * binToSigned((int[]){0,1,0,0, 0,0,0,1}, 0, 7) == -126 - * binToSigned((int[]){1,0,0,0, 0,0,0,1}, 0, 7) == -127 - * binToSigned((int[]){0,0,0,0, 0,0,0,1}, 0, 7) == -128 - * binToSigned((int[]){1,0, 1,1,1,0, 0,0}, 2, 5) == 7 - * binToSigned((int[]){1,0, 0,1,1,1, 0,0}, 2, 5) == -2 - */ -int binToSignedRev(const int *binary, int s, int e); // 0<=s<=e, binary[s(msb) .. e(lsb)] -int binToSigned(const int *binary, int s, int e); // 0<=s<=e, binary[s(lsb) .. e(msb)] - -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/core/common.h b/lib/ESPiLight/src/pilight/libs/pilight/core/common.h deleted file mode 100755 index c65491e9..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/core/common.h +++ /dev/null @@ -1 +0,0 @@ -/*dummy*/ diff --git a/lib/ESPiLight/src/pilight/libs/pilight/core/dso.h b/lib/ESPiLight/src/pilight/libs/pilight/core/dso.h deleted file mode 100644 index c32739ac..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/core/dso.h +++ /dev/null @@ -1,42 +0,0 @@ -/* - Copyright (C) 2013 CurlyMo - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#ifndef _DSO_H_ -#define _DSO_H_ - -typedef struct dso_t { - void *handle; - char *name; - ssize_t size; - struct dso_t *next; -} dso_t; - -typedef struct module_t { - const char *name; - const char *version; - const char *reqversion; - const char *reqcommit; -} module_t; - -struct dso_t *dso; - -void *dso_load(char *object); -int dso_gc(void); -void *dso_function(void *handle, const char *name); - -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/core/gc.h b/lib/ESPiLight/src/pilight/libs/pilight/core/gc.h deleted file mode 100755 index c65491e9..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/core/gc.h +++ /dev/null @@ -1 +0,0 @@ -/*dummy*/ diff --git a/lib/ESPiLight/src/pilight/libs/pilight/core/json.c b/lib/ESPiLight/src/pilight/libs/pilight/core/json.c deleted file mode 100644 index ee43d89a..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/core/json.c +++ /dev/null @@ -1,1443 +0,0 @@ -/* - Copyright (C) 2011 Joseph A. Adams (joeyadams3.14159@gmail.com) - All rights reserved. - - 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. -*/ - -#include -#include -#include -#include "../../../../tools/aprintf.h" -#include -#include - -#include "json.h" -#include "mem.h" - -#define out_of_memory() do { \ - fprintf(stderr, "Out of memory.\n"); \ - exit(EXIT_FAILURE); \ - } while (0) - -/* Sadly, strdup is not portable. */ -static char *json_strdup(const char *str) -{ - char *ret = (char*) malloc(strlen(str) + 1); - if (ret == NULL) - out_of_memory(); - memset(ret, 0, strlen(str) + 1); - strcpy(ret, str); - return ret; -} - -/* String buffer */ - -typedef struct -{ - char *cur; - char *end; - char *start; -} SB; - -static void sb_init(SB *sb) -{ - sb->start = (char*) malloc(17); - memset(sb->start, 0, 17); - if (sb->start == NULL) - out_of_memory(); - sb->cur = sb->start; - sb->end = sb->start + 16; -} - -/* sb and need may be evaluated multiple times. */ -#define sb_need(sb, need) do { \ - if ((sb)->end - (sb)->cur < (need)) \ - sb_grow(sb, need); \ - } while (0) - -static void sb_grow(SB *sb, int need) -{ - size_t length = sb->cur - sb->start; - size_t alloc = sb->end - sb->start; - - do { - alloc *= 2; - } while (alloc < length + need); - - sb->start = (char*) realloc(sb->start, alloc + 1); - if (sb->start == NULL) - out_of_memory(); - sb->cur = sb->start + length; - sb->end = sb->start + alloc; -} - -static void sb_put(SB *sb, const char *bytes, int count) -{ - sb_need(sb, count); - memcpy(sb->cur, bytes, count); - sb->cur += count; -} - -#define sb_putc(sb, c) do { \ - if ((sb)->cur >= (sb)->end) \ - sb_grow(sb, 1); \ - *(sb)->cur++ = (c); \ - } while (0) - -static void sb_puts(SB *sb, const char *str) -{ - sb_put(sb, str, strlen(str)); -} - -static char *sb_finish(SB *sb) -{ - *sb->cur = 0; - assert(sb->start <= sb->cur && strlen(sb->start) == (size_t)(sb->cur - sb->start)); - return sb->start; -} - -static void sb_free(SB *sb) -{ - free(sb->start); -} - -/* - * Unicode helper functions - * - * These are taken from the ccan/charset module and customized a bit. - * Putting them here means the compiler can (choose to) inline them, - * and it keeps ccan/json from having a dependency. - */ - -/* - * Type for Unicode codepoints. - * We need our own because wchar_t might be 16 bits. - */ -typedef uint32_t uchar_t; - -/* - * Validate a single UTF-8 character starting at @s. - * The string must be null-terminated. - * - * If it's valid, return its length (1 thru 4). - * If it's invalid or clipped, return 0. - * - * This function implements the syntax given in RFC3629, which is - * the same as that given in The Unicode Standard, Version 6.0. - * - * It has the following properties: - * - * * All codepoints U+0000..U+10FFFF may be encoded, - * except for U+D800..U+DFFF, which are reserved - * for UTF-16 surrogate pair encoding. - * * UTF-8 byte sequences longer than 4 bytes are not permitted, - * as they exceed the range of Unicode. - * * The sixty-six Unicode "non-characters" are permitted - * (namely, U+FDD0..U+FDEF, U+xxFFFE, and U+xxFFFF). - */ -static int utf8_validate_cz(const char *s) -{ - unsigned char c = *s++; - - if (c <= 0x7F) { /* 00..7F */ - return 1; - } else if (c <= 0xC1) { /* 80..C1 */ - /* Disallow overlong 2-byte sequence. */ - return 0; - } else if (c <= 0xDF) { /* C2..DF */ - /* Make sure subsequent byte is in the range 0x80..0xBF. */ - if (((unsigned char)*s++ & 0xC0) != 0x80) - return 0; - - return 2; - } else if (c <= 0xEF) { /* E0..EF */ - /* Disallow overlong 3-byte sequence. */ - if (c == 0xE0 && (unsigned char)*s < 0xA0) - return 0; - - /* Disallow U+D800..U+DFFF. */ - if (c == 0xED && (unsigned char)*s > 0x9F) - return 0; - - /* Make sure subsequent bytes are in the range 0x80..0xBF. */ - if (((unsigned char)*s++ & 0xC0) != 0x80) - return 0; - if (((unsigned char)*s++ & 0xC0) != 0x80) - return 0; - - return 3; - } else if (c <= 0xF4) { /* F0..F4 */ - /* Disallow overlong 4-byte sequence. */ - if (c == 0xF0 && (unsigned char)*s < 0x90) - return 0; - - /* Disallow codepoints beyond U+10FFFF. */ - if (c == 0xF4 && (unsigned char)*s > 0x8F) - return 0; - - /* Make sure subsequent bytes are in the range 0x80..0xBF. */ - if (((unsigned char)*s++ & 0xC0) != 0x80) - return 0; - if (((unsigned char)*s++ & 0xC0) != 0x80) - return 0; - if (((unsigned char)*s++ & 0xC0) != 0x80) - return 0; - - return 4; - } else { /* F5..FF */ - return 0; - } -} - -/* Validate a null-terminated UTF-8 string. */ -static bool utf8_validate(const char *s) -{ - int len; - - for (; *s != 0; s += len) { - len = utf8_validate_cz(s); - if (len == 0) - return false; - } - - return true; -} - -/* - * Read a single UTF-8 character starting at @s, - * returning the length, in bytes, of the character read. - * - * This function assumes input is valid UTF-8, - * and that there are enough characters in front of @s. - */ -static int utf8_read_char(const char *s, uchar_t *out) -{ - const unsigned char *c = (const unsigned char*) s; - - assert(utf8_validate_cz(s)); - - if (c[0] <= 0x7F) { - /* 00..7F */ - *out = c[0]; - return 1; - } else if (c[0] <= 0xDF) { - /* C2..DF (unless input is invalid) */ - *out = ((uchar_t)c[0] & 0x1F) << 6 | - ((uchar_t)c[1] & 0x3F); - return 2; - } else if (c[0] <= 0xEF) { - /* E0..EF */ - *out = ((uchar_t)c[0] & 0xF) << 12 | - ((uchar_t)c[1] & 0x3F) << 6 | - ((uchar_t)c[2] & 0x3F); - return 3; - } else { - /* F0..F4 (unless input is invalid) */ - *out = ((uchar_t)c[0] & 0x7) << 18 | - ((uchar_t)c[1] & 0x3F) << 12 | - ((uchar_t)c[2] & 0x3F) << 6 | - ((uchar_t)c[3] & 0x3F); - return 4; - } -} - -/* - * Write a single UTF-8 character to @s, - * returning the length, in bytes, of the character written. - * - * @unicode must be U+0000..U+10FFFF, but not U+D800..U+DFFF. - * - * This function will write up to 4 bytes to @out. - */ -static int utf8_write_char(uchar_t unicode, char *out) -{ - unsigned char *o = (unsigned char*) out; - - assert(unicode <= 0x10FFFF && !(unicode >= 0xD800 && unicode <= 0xDFFF)); - - if (unicode <= 0x7F) { - /* U+0000..U+007F */ - *o++ = unicode; - return 1; - } else if (unicode <= 0x7FF) { - /* U+0080..U+07FF */ - *o++ = 0xC0 | unicode >> 6; - *o++ = 0x80 | (unicode & 0x3F); - return 2; - } else if (unicode <= 0xFFFF) { - /* U+0800..U+FFFF */ - *o++ = 0xE0 | unicode >> 12; - *o++ = 0x80 | (unicode >> 6 & 0x3F); - *o++ = 0x80 | (unicode & 0x3F); - return 3; - } else { - /* U+10000..U+10FFFF */ - *o++ = 0xF0 | unicode >> 18; - *o++ = 0x80 | (unicode >> 12 & 0x3F); - *o++ = 0x80 | (unicode >> 6 & 0x3F); - *o++ = 0x80 | (unicode & 0x3F); - return 4; - } -} - -/* - * Compute the Unicode codepoint of a UTF-16 surrogate pair. - * - * @uc should be 0xD800..0xDBFF, and @lc should be 0xDC00..0xDFFF. - * If they aren't, this function returns false. - */ -static bool from_surrogate_pair(uint16_t uc, uint16_t lc, uchar_t *unicode) -{ - if (uc >= 0xD800 && uc <= 0xDBFF && lc >= 0xDC00 && lc <= 0xDFFF) { - *unicode = 0x10000 + ((((uchar_t)uc & 0x3FF) << 10) | (lc & 0x3FF)); - return true; - } else { - return false; - } -} - -/* - * Construct a UTF-16 surrogate pair given a Unicode codepoint. - * - * @unicode must be U+10000..U+10FFFF. - */ -static void to_surrogate_pair(uchar_t unicode, uint16_t *uc, uint16_t *lc) -{ - uchar_t n; - - assert(unicode >= 0x10000 && unicode <= 0x10FFFF); - - n = unicode - 0x10000; - *uc = ((n >> 10) & 0x3FF) | 0xD800; - *lc = (n & 0x3FF) | 0xDC00; -} - -#define is_space(c) ((c) == '\t' || (c) == '\n' || (c) == '\r' || (c) == ' ') -#define is_digit(c) ((c) >= '0' && (c) <= '9') - -static bool parse_value (const char **sp, JsonNode **out); -static bool parse_string (const char **sp, char **out); -static bool parse_number (const char **sp, double *out, int *decimals); -static bool parse_array (const char **sp, JsonNode **out); -static bool parse_object (const char **sp, JsonNode **out); -static bool parse_hex16 (const char **sp, uint16_t *out); - -static bool expect_literal (const char **sp, const char *str); -static void skip_space (const char **sp); - -static void emit_value (SB *out, const JsonNode *node); -static void emit_value_indented (SB *out, const JsonNode *node, const char *space, int indent_level); -static void emit_string (SB *out, const char *str); -static void emit_number (SB *out, double num, int decimals); -static void emit_array (SB *out, const JsonNode *array); -static void emit_array_indented (SB *out, const JsonNode *array, const char *space, int indent_level); -static void emit_object (SB *out, const JsonNode *object); -static void emit_object_indented (SB *out, const JsonNode *object, const char *space, int indent_level); - -static int write_hex16(char *out, uint16_t val); - -static JsonNode *mknode(JsonTag tag); -static void append_node(JsonNode *parent, JsonNode *child); -static void prepend_node(JsonNode *parent, JsonNode *child); -static void append_member(JsonNode *object, char *key, JsonNode *value); - -/* Assertion-friendly validity checks */ -static bool tag_is_valid(unsigned int tag); -static bool number_is_valid(const char *num); - -JsonNode *json_decode(const char *json) -{ - const char *s = json; - JsonNode *ret; - - skip_space(&s); - if (!parse_value(&s, &ret)) - return NULL; - - skip_space(&s); - if (*s != 0) { - json_delete(ret); - return NULL; - } - - return ret; -} - -char *json_encode(const JsonNode *node) -{ - return json_stringify(node, NULL); -} - -char *json_encode_string(const char *str) -{ - SB sb; - sb_init(&sb); - - emit_string(&sb, str); - - return sb_finish(&sb); -} - -char *json_stringify(const JsonNode *node, const char *space) -{ - SB sb; - sb_init(&sb); - - if (space != NULL) - emit_value_indented(&sb, node, space, 0); - else - emit_value(&sb, node); - - return sb_finish(&sb); -} - -void json_delete(JsonNode *node) -{ - if (node != NULL) { - json_remove_from_parent(node); - - switch (node->tag) { - case JSON_STRING: - free(node->string_); - break; - case JSON_ARRAY: - case JSON_OBJECT: - { - JsonNode *child, *next; - for (child = node->children.head; child != NULL; child = next) { - next = child->next; - json_delete(child); - } - break; - } - default:; - } - - free(node); - } -} - -bool json_validate(const char *json) -{ - const char *s = json; - - skip_space(&s); - if (!parse_value(&s, NULL)) - return false; - - skip_space(&s); - if (*s != 0) - return false; - - return true; -} - -JsonNode *json_find_element(JsonNode *array, int index) -{ - JsonNode *element; - int i = 0; - - if (array == NULL || array->tag != JSON_ARRAY) - return NULL; - - json_foreach(element, array) { - if (i == index) - return element; - i++; - } - - return NULL; -} - -JsonNode *json_find_member(JsonNode *object, const char *name) -{ - JsonNode *member; - - if (object == NULL || object->tag != JSON_OBJECT) - return NULL; - - json_foreach(member, object) - if (strcmp(member->key, name) == 0) - return member; - - return NULL; -} - -JsonNode *json_first_child(const JsonNode *node) -{ - if (node != NULL && (node->tag == JSON_ARRAY || node->tag == JSON_OBJECT)) - return node->children.head; - return NULL; -} - -static JsonNode *mknode(JsonTag tag) -{ - JsonNode *ret = (JsonNode*) calloc(1, sizeof(JsonNode)); - if (ret == NULL) - out_of_memory(); - ret->tag = tag; - return ret; -} - -JsonNode *json_mknull(void) -{ - return mknode(JSON_NULL); -} - -JsonNode *json_mkbool(bool b) -{ - JsonNode *ret = mknode(JSON_BOOL); - ret->bool_ = b; - return ret; -} - -static JsonNode *mkstring(char *s) -{ - JsonNode *ret = mknode(JSON_STRING); - ret->string_ = s; - return ret; -} - -JsonNode *json_mkstring(const char *s) -{ - return mkstring(json_strdup(s)); -} - -JsonNode *json_mknumber(double n, int decimals) -{ - JsonNode *node = mknode(JSON_NUMBER); - node->number_ = n; - node->decimals_ = decimals; - return node; -} - -JsonNode *json_mkarray(void) -{ - return mknode(JSON_ARRAY); -} - -JsonNode *json_mkobject(void) -{ - return mknode(JSON_OBJECT); -} - -static void append_node(JsonNode *parent, JsonNode *child) -{ - child->parent = parent; - child->prev = parent->children.tail; - child->next = NULL; - - if (parent->children.tail != NULL) - parent->children.tail->next = child; - else - parent->children.head = child; - parent->children.tail = child; -} - -static void prepend_node(JsonNode *parent, JsonNode *child) -{ - child->parent = parent; - child->prev = NULL; - child->next = parent->children.head; - - if (parent->children.head != NULL) - parent->children.head->prev = child; - else - parent->children.tail = child; - parent->children.head = child; -} - -static void append_member(JsonNode *object, char *key, JsonNode *value) -{ - value->key = key; - append_node(object, value); -} - -void json_append_element(JsonNode *array, JsonNode *element) -{ - assert(array->tag == JSON_ARRAY); - assert(element->parent == NULL); - - append_node(array, element); -} - -void json_prepend_element(JsonNode *array, JsonNode *element) -{ - assert(array->tag == JSON_ARRAY); - assert(element->parent == NULL); - - prepend_node(array, element); -} - -void json_append_member(JsonNode *object, const char *key, JsonNode *value) -{ - assert(object->tag == JSON_OBJECT); - assert(value->parent == NULL); - - append_member(object, json_strdup(key), value); -} - -void json_prepend_member(JsonNode *object, const char *key, JsonNode *value) -{ - assert(object->tag == JSON_OBJECT); - assert(value->parent == NULL); - - value->key = json_strdup(key); - prepend_node(object, value); -} - -void json_remove_from_parent(JsonNode *node) -{ - JsonNode *parent = node->parent; - - if (parent != NULL) { - if (node->prev != NULL) - node->prev->next = node->next; - else - parent->children.head = node->next; - if (node->next != NULL) - node->next->prev = node->prev; - else - parent->children.tail = node->prev; - - free(node->key); - - node->parent = NULL; - node->prev = node->next = NULL; - node->key = NULL; - } -} - -static bool parse_value(const char **sp, JsonNode **out) -{ - const char *s = *sp; - - switch (*s) { - case 'n': - if (expect_literal(&s, "null")) { - if (out) - *out = json_mknull(); - *sp = s; - return true; - } - return false; - - case 'f': - if (expect_literal(&s, "false")) { - if (out) - *out = json_mkbool(false); - *sp = s; - return true; - } - return false; - - case 't': - if (expect_literal(&s, "true")) { - if (out) - *out = json_mkbool(true); - *sp = s; - return true; - } - return false; - - case '"': { - char *str; - if (parse_string(&s, out ? &str : NULL)) { - if (out) - *out = mkstring(str); - *sp = s; - return true; - } - return false; - } - - case '[': - if (parse_array(&s, out)) { - *sp = s; - return true; - } - return false; - - case '{': - if (parse_object(&s, out)) { - *sp = s; - return true; - } - return false; - - default: { - double num; - int decimals = 0; - if (parse_number(&s, out ? &num : NULL, &decimals)) { - if (out) - *out = json_mknumber(num, decimals); - *sp = s; - return true; - } - return false; - } - } -} - -static bool parse_array(const char **sp, JsonNode **out) -{ - const char *s = *sp; - JsonNode *ret = out ? json_mkarray() : NULL; - JsonNode *element; - - if (*s++ != '[') - goto failure; - skip_space(&s); - - if (*s == ']') { - s++; - goto success; - } - - for (;;) { - if (!parse_value(&s, out ? &element : NULL)) - goto failure; - skip_space(&s); - - if (out) - json_append_element(ret, element); - - if (*s == ']') { - s++; - goto success; - } - - if (*s++ != ',') - goto failure; - skip_space(&s); - } - -success: - *sp = s; - if (out) - *out = ret; - return true; - -failure: - json_delete(ret); - return false; -} - -static bool parse_object(const char **sp, JsonNode **out) -{ - const char *s = *sp; - JsonNode *ret = out ? json_mkobject() : NULL; - char *key; - JsonNode *value; - - if (*s++ != '{') - goto failure; - skip_space(&s); - - if (*s == '}') { - s++; - goto success; - } - - for (;;) { - if (!parse_string(&s, out ? &key : NULL)) - goto failure; - skip_space(&s); - - if (*s++ != ':') - goto failure_free_key; - skip_space(&s); - - if (!parse_value(&s, out ? &value : NULL)) - goto failure_free_key; - skip_space(&s); - - if (out) - append_member(ret, key, value); - - if (*s == '}') { - s++; - goto success; - } - - if (*s++ != ',') - goto failure; - skip_space(&s); - } - -success: - *sp = s; - if (out) - *out = ret; - return true; - -failure_free_key: - if (out) - free(key); -failure: - json_delete(ret); - return false; -} - -bool parse_string(const char **sp, char **out) -{ - const char *s = *sp; - SB sb; - char throwaway_buffer[4]; - /* enough space for a UTF-8 character */ - char *b; - - if (*s++ != '"') - return false; - - if (out) { - sb_init(&sb); - sb_need(&sb, 4); - b = sb.cur; - } else { - b = throwaway_buffer; - } - - while (*s != '"') { - unsigned char c = *s++; - - /* Parse next character, and write it to b. */ - if (c == '\\') { - c = *s++; - switch (c) { - case '"': - case '\\': - case '/': - *b++ = c; - break; - case 'b': - *b++ = '\b'; - break; - case 'f': - *b++ = '\f'; - break; - case 'n': - *b++ = '\n'; - break; - case 'r': - *b++ = '\r'; - break; - case 't': - *b++ = '\t'; - break; - case 'u': - { - uint16_t uc, lc; - uchar_t unicode; - - if (!parse_hex16(&s, &uc)) - goto failed; - - if (uc >= 0xD800 && uc <= 0xDFFF) { - /* Handle UTF-16 surrogate pair. */ - if (*s++ != '\\' || *s++ != 'u' || !parse_hex16(&s, &lc)) - goto failed; /* Incomplete surrogate pair. */ - if (!from_surrogate_pair(uc, lc, &unicode)) - goto failed; /* Invalid surrogate pair. */ - } else if (uc == 0) { - /* Disallow "\u0000". */ - goto failed; - } else { - unicode = uc; - } - - b += utf8_write_char(unicode, b); - break; - } - default: - /* Invalid escape */ - goto failed; - } - } else if (c <= 0x1F) { - /* Control characters are not allowed in string literals. */ - goto failed; - } else { - /* Validate and echo a UTF-8 character. */ - int len; - - s--; - len = utf8_validate_cz(s); - if (len == 0) - goto failed; /* Invalid UTF-8 character. */ - - while (len--) - *b++ = *s++; - } - - /* - * Update sb to know about the new bytes, - * and set up b to write another character. - */ - if (out) { - sb.cur = b; - sb_need(&sb, 4); - b = sb.cur; - } else { - b = throwaway_buffer; - } - } - s++; - - if (out) - *out = sb_finish(&sb); - *sp = s; - return true; - -failed: - if (out) - sb_free(&sb); - return false; -} - -/* - * The JSON spec says that a number shall follow this precise pattern - * (spaces and quotes added for readability): - * '-'? (0 | [1-9][0-9]*) ('.' [0-9]+)? ([Ee] [+-]? [0-9]+)? - * - * However, some JSON parsers are more liberal. For instance, PHP accepts - * '.5' and '1.'. JSON.parse accepts '+3'. - * - * This function takes the strict approach. - */ -bool parse_number(const char **sp, double *out, int *decimals) -{ - const char *s = *sp; - if(decimals != NULL) { - (*decimals) = 0; - } - - /* '-'? */ - if (*s == '-') - s++; - - /* (0 | [1-9][0-9]*) */ - if (*s == '0') { - s++; - } else { - if (!is_digit(*s)) - return false; - do { - s++; - } while (is_digit(*s)); - } - - /* ('.' [0-9]+)? */ - if (*s == '.') { - s++; - if (!is_digit(*s)) - return false; - do { - s++; - if(decimals != NULL) { - (*decimals)++; - } - } while (is_digit(*s)); - } - - /* ([Ee] [+-]? [0-9]+)? */ - if (*s == 'E' || *s == 'e') { - s++; - if (*s == '+' || *s == '-') - s++; - if (!is_digit(*s)) - return false; - do { - s++; - } while (is_digit(*s)); - } - - if (out) - *out = strtod(*sp, NULL); - - *sp = s; - return true; -} - -static void skip_space(const char **sp) -{ - const char *s = *sp; - while (is_space(*s)) - s++; - *sp = s; -} - -static void emit_value(SB *out, const JsonNode *node) -{ - assert(tag_is_valid(node->tag)); - switch (node->tag) { - case JSON_NULL: - sb_puts(out, "null"); - break; - case JSON_BOOL: - sb_puts(out, node->bool_ ? "true" : "false"); - break; - case JSON_STRING: - emit_string(out, node->string_); - break; - case JSON_NUMBER: - emit_number(out, node->number_, node->decimals_); - break; - case JSON_ARRAY: - emit_array(out, node); - break; - case JSON_OBJECT: - emit_object(out, node); - break; - default: - assert(false); - } -} - -void emit_value_indented(SB *out, const JsonNode *node, const char *space, int indent_level) -{ - assert(tag_is_valid(node->tag)); - switch (node->tag) { - case JSON_NULL: - sb_puts(out, "null"); - break; - case JSON_BOOL: - sb_puts(out, node->bool_ ? "true" : "false"); - break; - case JSON_STRING: - emit_string(out, node->string_); - break; - case JSON_NUMBER: - emit_number(out, node->number_, node->decimals_); - break; - case JSON_ARRAY: - emit_array_indented(out, node, space, indent_level); - break; - case JSON_OBJECT: - emit_object_indented(out, node, space, indent_level); - break; - default: - assert(false); - } -} - -static void emit_array_indented(SB *out, const JsonNode *array, const char *space, int indent_level) -{ - const JsonNode *element = array->children.head; - const JsonNode *tmp = json_first_child(array); - int i, x; - - if(tmp && (tmp->tag == JSON_STRING || tmp->tag == JSON_NUMBER)) { - const JsonNode *element1 = array->children.head; - - if (element1 == NULL) { - sb_puts(out, "[]"); - return; - } - - sb_puts(out, "[ "); - while (element1 != NULL) { - emit_value(out, element1); - element1 = element1->next; - sb_puts(out, element1 != NULL ? ", " : ""); - } - sb_puts(out, " ]"); - } else { - if (element == NULL) { - sb_puts(out, "[]"); - return; - } - - sb_puts(out, "["); - x = 0; - while (element != NULL) { - x++; - if(x > 1) { - for (i = 0; i < indent_level; i++) - sb_puts(out, space); - } - emit_value_indented(out, element, space, indent_level); - element = element->next; - sb_puts(out, element != NULL ? ",\n" : ""); - } - sb_puts(out, "]"); - } -} - -static void emit_array(SB *out, const JsonNode *array) -{ - const JsonNode *element = array->children.head; - - if (element == NULL) { - sb_puts(out, "[]"); - return; - } - - sb_puts(out, "["); - while (element != NULL) { - emit_value(out, element); - element = element->next; - sb_puts(out, element != NULL ? "," : ""); - } - sb_puts(out, "]"); -} - -static void emit_object(SB *out, const JsonNode *object) -{ - const JsonNode *member; - - sb_putc(out, '{'); - json_foreach(member, object) { - emit_string(out, member->key); - sb_putc(out, ':'); - emit_value(out, member); - if (member->next != NULL) - sb_putc(out, ','); - } - sb_putc(out, '}'); -} - -static void emit_object_indented(SB *out, const JsonNode *object, const char *space, int indent_level) -{ - const JsonNode *member = object->children.head; - int i; - - if (member == NULL) { - sb_puts(out, "{}"); - return; - } - - sb_puts(out, "{\n"); - while (member != NULL) { - for (i = 0; i < indent_level + 1; i++) - sb_puts(out, space); - emit_string(out, member->key); - sb_puts(out, ": "); - emit_value_indented(out, member, space, indent_level + 1); - - member = member->next; - sb_puts(out, member != NULL ? ",\n" : "\n"); - } - for (i = 0; i < indent_level; i++) - sb_puts(out, space); - sb_putc(out, '}'); -} - -void emit_string(SB *out, const char *str) -{ - bool escape_unicode = false; - const char *s = str; - char *b; - - assert(utf8_validate(str)); - - /* - * 14 bytes is enough space to write up to two - * \uXXXX escapes and two quotation marks. - */ - sb_need(out, 14); - b = out->cur; - - *b++ = '"'; - while (*s != 0) { - unsigned char c = *s++; - - /* Encode the next character, and write it to b. */ - switch (c) { - case '"': - *b++ = '\\'; - *b++ = '"'; - break; - case '\\': - *b++ = '\\'; - *b++ = '\\'; - break; - case '\b': - *b++ = '\\'; - *b++ = 'b'; - break; - case '\f': - *b++ = '\\'; - *b++ = 'f'; - break; - case '\n': - *b++ = '\\'; - *b++ = 'n'; - break; - case '\r': - *b++ = '\\'; - *b++ = 'r'; - break; - case '\t': - *b++ = '\\'; - *b++ = 't'; - break; - default: { - int len; - - s--; - len = utf8_validate_cz(s); - - if (len == 0) { - /* - * Handle invalid UTF-8 character gracefully in production - * by writing a replacement character (U+FFFD) - * and skipping a single byte. - * - * This should never happen when assertions are enabled - * due to the assertion at the beginning of this function. - */ - assert(false); - if (escape_unicode) { - strcpy(b, "\\uFFFD"); - b += 6; - } else { - *b++ = 0xEF; - *b++ = 0xBF; - *b++ = 0xBD; - } - s++; - } else if (c < 0x1F || (c >= 0x80 && escape_unicode)) { - /* Encode using \u.... */ - uint32_t unicode; - - s += utf8_read_char(s, &unicode); - - if (unicode <= 0xFFFF) { - *b++ = '\\'; - *b++ = 'u'; - b += write_hex16(b, unicode); - } else { - /* Produce a surrogate pair. */ - uint16_t uc, lc; - assert(unicode <= 0x10FFFF); - to_surrogate_pair(unicode, &uc, &lc); - *b++ = '\\'; - *b++ = 'u'; - b += write_hex16(b, uc); - *b++ = '\\'; - *b++ = 'u'; - b += write_hex16(b, lc); - } - } else { - /* Write the character directly. */ - while (len--) - *b++ = *s++; - } - - break; - } - } - - /* - * Update *out to know about the new bytes, - * and set up b to write another encoded character. - */ - out->cur = b; - sb_need(out, 14); - b = out->cur; - } - *b++ = '"'; - - out->cur = b; -} - -static void emit_number(SB *out, double num, int decimals) -{ - /* - * This isn't exactly how JavaScript renders numbers, - * but it should produce valid JSON for reasonable numbers - * preserve precision well enough, and avoid some oddities - * like 0.3 -> 0.299999999999999988898 . - */ - char buf[64]; -#ifdef ESP8266 - dtostrf(num, 0, decimals, buf); -#else - sprintf(buf, "%.*f", decimals, num); -#endif - - if (number_is_valid(buf)) - sb_puts(out, buf); - else - sb_puts(out, "null"); -} - -static bool tag_is_valid(unsigned int tag) -{ - return (/* tag >= JSON_NULL && */ tag <= JSON_OBJECT); -} - -static bool number_is_valid(const char *num) -{ - return (parse_number(&num, NULL, NULL) && *num == '\0'); -} - -static bool expect_literal(const char **sp, const char *str) -{ - const char *s = *sp; - - while (*str != '\0') - if (*s++ != *str++) - return false; - - *sp = s; - return true; -} - -/* - * Parses exactly 4 hex characters (capital or lowercase). - * Fails if any input chars are not [0-9A-Fa-f]. - */ -static bool parse_hex16(const char **sp, uint16_t *out) -{ - const char *s = *sp; - uint16_t ret = 0; - uint16_t i; - uint16_t tmp; - char c; - - for (i = 0; i < 4; i++) { - c = *s++; - if (c >= '0' && c <= '9') - tmp = c - '0'; - else if (c >= 'A' && c <= 'F') - tmp = c - 'A' + 10; - else if (c >= 'a' && c <= 'f') - tmp = c - 'a' + 10; - else - return false; - - ret <<= 4; - ret += tmp; - } - - if (out) - *out = ret; - *sp = s; - return true; -} - -/* - * Encodes a 16-bit number into hexadecimal, - * writing exactly 4 hex chars. - */ -static int write_hex16(char *out, uint16_t val) -{ - const char *hex = "0123456789ABCDEF"; - - *out++ = hex[(val >> 12) & 0xF]; - *out++ = hex[(val >> 8) & 0xF]; - *out++ = hex[(val >> 4) & 0xF]; - *out++ = hex[ val & 0xF]; - - return 4; -} - -bool json_check(const JsonNode *node, char errmsg[256]) -{ - #define problem(...) do { \ - if (errmsg != NULL) \ - snprintf(errmsg, 256, __VA_ARGS__); \ - return false; \ - } while (0) - - if (node->key != NULL && !utf8_validate(node->key)) - problem("key contains invalid UTF-8"); - - if (!tag_is_valid(node->tag)) - problem("tag is invalid (%u)", node->tag); - - if (node->tag == JSON_BOOL) { - if (node->bool_ != false && node->bool_ != true) - problem("bool_ is neither false (%d) nor true (%d)", (int)false, (int)true); - } else if (node->tag == JSON_STRING) { - if (node->string_ == NULL) - problem("string_ is NULL"); - if (!utf8_validate(node->string_)) - problem("string_ contains invalid UTF-8"); - } else if (node->tag == JSON_ARRAY || node->tag == JSON_OBJECT) { - JsonNode *head = node->children.head; - JsonNode *tail = node->children.tail; - - if (head == NULL || tail == NULL) { - if (head != NULL) - problem("tail is NULL, but head is not"); - if (tail != NULL) - problem("head is NULL, but tail is not"); - } else { - JsonNode *child; - JsonNode *last = NULL; - - if (head->prev != NULL) - problem("First child's prev pointer is not NULL"); - - for (child = head; child != NULL; last = child, child = child->next) { - if (child == node) - problem("node is its own child"); - if (child->next == child) - problem("child->next == child (cycle)"); - if (child->next == head) - problem("child->next == head (cycle)"); - - if (child->parent != node) - problem("child does not point back to parent"); - if (child->next != NULL && child->next->prev != child) - problem("child->next does not point back to child"); - - if (node->tag == JSON_ARRAY && child->key != NULL) - problem("Array element's key is not NULL"); - if (node->tag == JSON_OBJECT && child->key == NULL) - problem("Object member's key is NULL"); - - if (!json_check(child, errmsg)) - return false; - } - - if (last != tail) - problem("tail does not match pointer found by starting at head and following next links"); - } - } - - return true; - - #undef problem -} - -int json_find_number(JsonNode *object, const char *name, double *out) { - JsonNode *node = json_find_member(object, name); - if (node && node->tag == JSON_NUMBER) { - *out = node->number_; - return 0; - } - return 1; -} - -int json_find_string(JsonNode *object, const char *name, char **out) { - JsonNode *node = json_find_member(object, name); - if (node && node->tag == JSON_STRING) { - *out = node->string_; - return 0; - } - return 1; -} - -void json_free(void *a) { - free(a); -} diff --git a/lib/ESPiLight/src/pilight/libs/pilight/core/json.h b/lib/ESPiLight/src/pilight/libs/pilight/core/json.h deleted file mode 100644 index b6526d98..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/core/json.h +++ /dev/null @@ -1,124 +0,0 @@ -/* - Copyright (C) 2013 - 2014 CurlyMo (curlymoo1@gmail.com) - 2011 Joseph A. Adams (joeyadams3.14159@gmail.com) - All rights reserved. - - 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. -*/ - -#ifndef CCAN_JSON_H -#define CCAN_JSON_H - -#include -#include - -#define JSON_NULL 0x01 -#define JSON_BOOL 0x01 << 1 -#define JSON_STRING 0x01 << 2 -#define JSON_NUMBER 0x01 << 3 -#define JSON_ARRAY 0x01 << 4 -#define JSON_OBJECT 0x01 << 5 - -#define JsonTag int - -typedef struct JsonNode JsonNode; - -struct JsonNode -{ - /* only if parent is an object or array (NULL otherwise) */ - JsonNode *parent; - JsonNode *prev, *next; - - /* only if parent is an object (NULL otherwise) */ - char *key; /* Must be valid UTF-8. */ - - JsonTag tag; - union { - /* JSON_BOOL */ - bool bool_; - - /* JSON_STRING */ - char *string_; /* Must be valid UTF-8. */ - - /* JSON_NUMBER */ - double number_; - - /* JSON_ARRAY */ - /* JSON_OBJECT */ - struct { - JsonNode *head, *tail; - } children; - }; - int decimals_; -}; - -/*** Encoding, decoding, and validation ***/ - -JsonNode *json_decode (const char *json); -char *json_encode (const JsonNode *node); -char *json_encode_string (const char *str); -char *json_stringify (const JsonNode *node, const char *space); -void json_delete (JsonNode *node); - -bool json_validate (const char *json); - -/*** Lookup and traversal ***/ - -JsonNode *json_find_element (JsonNode *array, int index); -JsonNode *json_find_member (JsonNode *object, const char *key); - -JsonNode *json_first_child (const JsonNode *node); - -#define json_foreach(i, object_or_array) \ - for ((i) = json_first_child(object_or_array); \ - (i) != NULL; \ - (i) = (i)->next) - -/*** Construction and manipulation ***/ - -JsonNode *json_mknull(void); -JsonNode *json_mkbool(bool b); -JsonNode *json_mkstring(const char *s); -JsonNode *json_mknumber(double n, int decimals); -JsonNode *json_mkarray(void); -JsonNode *json_mkobject(void); - -void json_append_element(JsonNode *array, JsonNode *element); -void json_prepend_element(JsonNode *array, JsonNode *element); -void json_append_member(JsonNode *object, const char *key, JsonNode *value); -void json_prepend_member(JsonNode *object, const char *key, JsonNode *value); - -void json_remove_from_parent(JsonNode *node); - -void json_free(void *a); - -/*** Debugging ***/ - -/* - * Look for structure and encoding problems in a JsonNode or its descendents. - * - * If a problem is detected, return false, writing a description of the problem - * to errmsg (unless errmsg is NULL). - */ -bool json_check(const JsonNode *node, char errmsg[256]); - -int json_find_number(JsonNode *object, const char *name, double *out); -int json_find_string(JsonNode *object, const char *name, char **out); - -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/core/log.h b/lib/ESPiLight/src/pilight/libs/pilight/core/log.h deleted file mode 100755 index 71da84f6..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/core/log.h +++ /dev/null @@ -1,37 +0,0 @@ -/* - ESPiLight - pilight 433.92 MHz protocols library for Arduino - Copyright (c) 2016 Puuu. All right reserved. - - Project home: https://github.com/puuu/espilight/ - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 3 of the License, or (at your option) any later version. - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU General Public License - along with library. If not, see -*/ - -#ifndef _LOG_H_ -#define _LOG_H_ - -#define LOG_EMERG 0 -#define LOG_ALERT 1 -#define LOG_CRIT 2 -#define LOG_ERR 3 -#define LOG_WARNING 4 -#define LOG_NOTICE 5 -#define LOG_INFO 6 -#define LOG_DEBUG 7 - -#define LOG_STACK 255 - -#include - -#define logprintf(prio, args...) {printf("pilight(%d): ", prio);printf(args);printf("\n");} - -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/core/mem.h b/lib/ESPiLight/src/pilight/libs/pilight/core/mem.h deleted file mode 100644 index 7715d2a7..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/core/mem.h +++ /dev/null @@ -1,44 +0,0 @@ -/* - Copyright (C) 2013 - 2016 CurlyMo - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. -*/ - -#ifndef _MEM_H_ -#define _MEM_H_ - -#define OUT_OF_MEMORY fprintf(stderr, "out of memory in %s #%d\n", __FILE__, __LINE__),exit(EXIT_FAILURE); - -int xfree(void); -void memtrack(void); - -void *__malloc(unsigned long, const char *, int); -void *__realloc(void *, unsigned long, const char *, int); -void *__calloc(unsigned long a, unsigned long b, const char *, int); -void __free(void *, const char *, int); -/* - * Windows already has a _strdup, libpcap uses __strdup - */ -char *___strdup(char *, const char *, int); - -// #define MALLOC(a) __malloc(a, __FILE__, __LINE__) -// #define REALLOC(a, b) __realloc(a, b, __FILE__, __LINE__) -// #define CALLOC(a, b) __calloc(a, b, __FILE__, __LINE__) -// #define STRDUP(a) ___strdup(a, __FILE__, __LINE__) -// #define FREE(a) __free((void *)(a), __FILE__, __LINE__),(a)=NULL - -#define MALLOC malloc -#define REALLOC realloc -#define CALLOC calloc -#define STRDUP strdup -#define FREE(a) free((void *)(a)),(a)=NULL - -#define _MALLOC malloc -#define _REALLOC realloc -#define _CALLOC calloc -#define _STRDUP strdup -#define _FREE free - -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/core/pilight.h b/lib/ESPiLight/src/pilight/libs/pilight/core/pilight.h deleted file mode 100755 index e10475f0..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/core/pilight.h +++ /dev/null @@ -1,29 +0,0 @@ -/* - ESPiLight - pilight 433.92 MHz protocols library for Arduino - Copyright (c) 2016 Puuu. All right reserved. - - Project home: https://github.com/puuu/espilight/ - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 3 of the License, or (at your option) any later version. - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU General Public License - along with library. If not, see -*/ - -#ifndef _PILIGHT_H_ -#define _PILIGHT_H_ - -//#include "defines.h" -#define PULSE_DIV 34 -#define EPSILON 0.00001 - -#include "mem.h" -#include "../../../../tools/aprintf.h" - -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/alecto_ws1700.c b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/alecto_ws1700.c deleted file mode 100644 index 370053d8..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/alecto_ws1700.c +++ /dev/null @@ -1,218 +0,0 @@ -/* - Copyright (C) 2014 CurlyMo - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#include -#include -#include -#include - -#include "../../core/pilight.h" -#include "../../core/common.h" -#include "../../core/dso.h" -#include "../../core/log.h" -#include "../protocol.h" -#include "../../core/binary.h" -#include "../../core/gc.h" -#include "alecto_ws1700.h" - -#define PULSE_MULTIPLIER 20 -#define MIN_PULSE_LENGTH 261 -#define AVG_PULSE_LENGTH 266 -#define MAX_PULSE_LENGTH 280 -#define RAW_LENGTH 74 - -typedef struct settings_t { - double id; - double temp; - double humi; - struct settings_t *next; -} settings_t; - -static struct settings_t *settings = NULL; - -static int validate(void) { - if(alecto_ws1700->rawlen == RAW_LENGTH) { - if(alecto_ws1700->raw[alecto_ws1700->rawlen-1] >= (MIN_PULSE_LENGTH*PULSE_DIV) && - alecto_ws1700->raw[alecto_ws1700->rawlen-1] <= (MAX_PULSE_LENGTH*PULSE_DIV)) { - return 0; - } - } - - return -1; -} - -static void parseCode(void) { - int i = 0, x = 0, binary[RAW_LENGTH/2]; - int id = 0, battery = 0, header = 0; - double humi_offset = 0.0, temp_offset = 0.0; - double temperature = 0.0, humidity = 0.0; - - if(alecto_ws1700->rawlen>RAW_LENGTH) { - logprintf(LOG_ERR, "alecto_ws1700: parsecode - invalid parameter passed %d", alecto_ws1700->rawlen); - return; - } - - for(x=1;xrawlen-1;x+=2) { - if(alecto_ws1700->raw[x] > (int)((double)AVG_PULSE_LENGTH*((double)PULSE_MULTIPLIER/2))) { - binary[i++] = 1; - } else { - binary[i++] = 0; - } - } - - header = binToDecRev(binary, 0, 3); - if (header != 5) { - return; - } - id = binToDecRev(binary, 4, 11); - battery = binary[12]; - temperature = (double)binToSignedRev(binary, 16, 27); - humidity = (double)binToDecRev(binary, 28, 35); - - temperature /= 10; - - struct settings_t *tmp = settings; - while(tmp) { - if(fabs(tmp->id-id) < EPSILON) { - humi_offset = tmp->humi; - temp_offset = tmp->temp; - break; - } - tmp = tmp->next; - } - - temperature += temp_offset; - humidity += humi_offset; - - alecto_ws1700->message = json_mkobject(); - json_append_member(alecto_ws1700->message, "id", json_mknumber(id, 0)); - json_append_member(alecto_ws1700->message, "temperature", json_mknumber(temperature, 1)); - json_append_member(alecto_ws1700->message, "humidity", json_mknumber(humidity, 1)); - json_append_member(alecto_ws1700->message, "battery", json_mknumber(battery, 0)); -} - -static int checkValues(struct JsonNode *jvalues) { - struct JsonNode *jid = NULL; - - if((jid = json_find_member(jvalues, "id"))) { - struct settings_t *snode = NULL; - struct JsonNode *jchild = NULL; - struct JsonNode *jchild1 = NULL; - double id = -1; - int match = 0; - - jchild = json_first_child(jid); - while(jchild) { - jchild1 = json_first_child(jchild); - while(jchild1) { - if(strcmp(jchild1->key, "id") == 0) { - id = jchild1->number_; - } - jchild1 = jchild1->next; - } - jchild = jchild->next; - } - - struct settings_t *tmp = settings; - while(tmp) { - if(fabs(tmp->id-id) < EPSILON) { - match = 1; - break; - } - tmp = tmp->next; - } - - if(match == 0) { - if((snode = MALLOC(sizeof(struct settings_t))) == NULL) { - fprintf(stderr, "out of memory\n"); - exit(EXIT_FAILURE); - } - snode->id = id; - snode->temp = 0; - snode->humi = 0; - - json_find_number(jvalues, "temperature-offset", &snode->temp); - json_find_number(jvalues, "humidity-offset", &snode->humi); - - snode->next = settings; - settings = snode; - } - } - return 0; -} - -static void gc(void) { - struct settings_t *tmp = NULL; - while(settings) { - tmp = settings; - settings = settings->next; - FREE(tmp); - } - if(settings != NULL) { - FREE(settings); - } -} - -#if !defined(MODULE) && !defined(_WIN32) -__attribute__((weak)) -#endif -void alectoWS1700Init(void) { - - protocol_register(&alecto_ws1700); - protocol_set_id(alecto_ws1700, "alecto_ws1700"); - protocol_device_add(alecto_ws1700, "alecto_ws1700", "Alecto WS1700 Weather Stations"); - protocol_device_add(alecto_ws1700, "iboutique", "iBoutique Weather Stations"); - alecto_ws1700->devtype = WEATHER; - alecto_ws1700->hwtype = RF433; - alecto_ws1700->minrawlen = RAW_LENGTH; - alecto_ws1700->maxrawlen = RAW_LENGTH; - alecto_ws1700->maxgaplen = MAX_PULSE_LENGTH*PULSE_DIV; - alecto_ws1700->mingaplen = MIN_PULSE_LENGTH*PULSE_DIV; - - options_add(&alecto_ws1700->options, "t", "temperature", OPTION_HAS_VALUE, DEVICES_VALUE, JSON_NUMBER, NULL, "^[0-9]{1,3}$"); - options_add(&alecto_ws1700->options, "i", "id", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, "[0-9]"); - options_add(&alecto_ws1700->options, "h", "humidity", OPTION_HAS_VALUE, DEVICES_VALUE, JSON_NUMBER, NULL, "[0-9]"); - options_add(&alecto_ws1700->options, "b", "battery", OPTION_HAS_VALUE, DEVICES_VALUE, JSON_NUMBER, NULL, "^[01]$"); - - // options_add(&alecto_ws1700->options, "0", "decimals", OPTION_HAS_VALUE, DEVICES_SETTING, JSON_NUMBER, (void *)1, "[0-9]"); - options_add(&alecto_ws1700->options, "0", "temperature-offset", OPTION_HAS_VALUE, DEVICES_SETTING, JSON_NUMBER, (void *)0, "[0-9]"); - options_add(&alecto_ws1700->options, "0", "humidity-offset", OPTION_HAS_VALUE, DEVICES_SETTING, JSON_NUMBER, (void *)0, "[0-9]"); - options_add(&alecto_ws1700->options, "0", "temperature-decimals", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)1, "[0-9]"); - options_add(&alecto_ws1700->options, "0", "humidity-decimals", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)1, "[0-9]"); - options_add(&alecto_ws1700->options, "0", "show-humidity", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)1, "^[10]{1}$"); - options_add(&alecto_ws1700->options, "0", "show-temperature", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)1, "^[10]{1}$"); - options_add(&alecto_ws1700->options, "0", "show-battery", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)1, "^[10]{1}$"); - - alecto_ws1700->parseCode=&parseCode; - alecto_ws1700->checkValues=&checkValues; - alecto_ws1700->validate=&validate; - alecto_ws1700->gc=&gc; -} - -#if defined(MODULE) && !defined(_WIN32) -void compatibility(struct module_t *module) { - module->name = "alecto_ws1700"; - module->version = "2.5"; - module->reqversion = "6.0"; - module->reqcommit = "84"; -} - -void init(void) { - alectoWS1700Init(); -} -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/alecto_ws1700.h b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/alecto_ws1700.h deleted file mode 100644 index 10bc16b9..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/alecto_ws1700.h +++ /dev/null @@ -1,27 +0,0 @@ -/* - Copyright (C) 2013 CurlyMo - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#ifndef _PROTOCOL_WS1700_H_ -#define _PROTOCOL_WS1700_H_ - -#include "../protocol.h" - -struct protocol_t *alecto_ws1700; -void alectoWS1700Init(void); - -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/alecto_wsd17.c b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/alecto_wsd17.c deleted file mode 100644 index 8fee3901..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/alecto_wsd17.c +++ /dev/null @@ -1,193 +0,0 @@ -/* - Copyright (C) 2014 CurlyMo - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#include -#include -#include -#include - -#include "../../core/pilight.h" -#include "../../core/common.h" -#include "../../core/dso.h" -#include "../../core/log.h" -#include "../protocol.h" -#include "../../core/binary.h" -#include "../../core/gc.h" -#include "alecto_wsd17.h" - -#define PULSE_MULTIPLIER 14 -#define MIN_PULSE_LENGTH 265 -#define AVG_PULSE_LENGTH 270 -#define MAX_PULSE_LENGTH 275 -#define RAW_LENGTH 74 - -typedef struct settings_t { - double id; - double temp; - struct settings_t *next; -} settings_t; - -static struct settings_t *settings = NULL; - -static int validate(void) { - if(alecto_wsd17->rawlen == RAW_LENGTH) { - if(alecto_wsd17->raw[alecto_wsd17->rawlen-1] >= (MIN_PULSE_LENGTH*PULSE_DIV) && - alecto_wsd17->raw[alecto_wsd17->rawlen-1] <= (MAX_PULSE_LENGTH*PULSE_DIV)) { - return 0; - } - } - - return -1; -} - -static void parseCode(void) { - int i = 0, x = 0, id = 0, binary[RAW_LENGTH/2]; - double temp_offset = 0.0, temperature = 0.0; - - if(alecto_wsd17->rawlen>RAW_LENGTH) { - logprintf(LOG_ERR, "alecto_wsd17: parsecode - invalid parameter passed %d", alecto_wsd17->rawlen); - return; - } - - for(x=1;xrawlen-1;x+=2) { - if(alecto_wsd17->raw[x] > (int)((double)AVG_PULSE_LENGTH*((double)PULSE_MULTIPLIER/2))) { - binary[i++] = 1; - } else { - binary[i++] = 0; - } - } - - id = binToDecRev(binary, 0, 11); - temperature = binToDecRev(binary, 16, 27); - - struct settings_t *tmp = settings; - while(tmp) { - if(fabs(tmp->id-id) < EPSILON) { - temp_offset = tmp->temp; - break; - } - tmp = tmp->next; - } - - temperature += temp_offset; - - alecto_wsd17->message = json_mkobject(); - json_append_member(alecto_wsd17->message, "id", json_mknumber(id, 0)); - json_append_member(alecto_wsd17->message, "temperature", json_mknumber(temperature/10, 1)); -} - -static int checkValues(struct JsonNode *jvalues) { - struct JsonNode *jid = NULL; - - if((jid = json_find_member(jvalues, "id"))) { - struct settings_t *snode = NULL; - struct JsonNode *jchild = NULL; - struct JsonNode *jchild1 = NULL; - double id = -1; - int match = 0; - - jchild = json_first_child(jid); - while(jchild) { - jchild1 = json_first_child(jchild); - while(jchild1) { - if(strcmp(jchild1->key, "id") == 0) { - id = jchild1->number_; - } - jchild1 = jchild1->next; - } - jchild = jchild->next; - } - - struct settings_t *tmp = settings; - while(tmp) { - if(fabs(tmp->id-id) < EPSILON) { - match = 1; - break; - } - tmp = tmp->next; - } - - if(match == 0) { - if((snode = MALLOC(sizeof(struct settings_t))) == NULL) { - fprintf(stderr, "out of memory\n"); - exit(EXIT_FAILURE); - } - snode->id = id; - snode->temp = 0; - - json_find_number(jvalues, "temperature-offset", &snode->temp); - - snode->next = settings; - settings = snode; - } - } - return 0; -} - -static void gc(void) { - struct settings_t *tmp = NULL; - while(settings) { - tmp = settings; - settings = settings->next; - FREE(tmp); - } - if(settings != NULL) { - FREE(settings); - } -} - -#if !defined(MODULE) && !defined(_WIN32) -__attribute__((weak)) -#endif -void alectoWSD17Init(void) { - protocol_register(&alecto_wsd17); - protocol_set_id(alecto_wsd17, "alecto_wsd17"); - protocol_device_add(alecto_wsd17, "alecto_wsd17", "Alecto WSD-17 Weather Stations"); - alecto_wsd17->devtype = WEATHER; - alecto_wsd17->hwtype = RF433; - alecto_wsd17->minrawlen = RAW_LENGTH; - alecto_wsd17->maxrawlen = RAW_LENGTH; - alecto_wsd17->maxgaplen = MAX_PULSE_LENGTH*PULSE_DIV; - alecto_wsd17->mingaplen = MIN_PULSE_LENGTH*PULSE_DIV; - - options_add(&alecto_wsd17->options, "t", "temperature", OPTION_HAS_VALUE, DEVICES_VALUE, JSON_NUMBER, NULL, "^[0-9]{1,3}$"); - options_add(&alecto_wsd17->options, "i", "id", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, "[0-9]"); - - // options_add(&alecto_wsd17->options, "0", "decimals", OPTION_HAS_VALUE, DEVICES_SETTING, JSON_NUMBER, (void *)1, "[0-9]"); - options_add(&alecto_wsd17->options, "0", "temperature-decimals", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)1, "[0-9]"); - options_add(&alecto_wsd17->options, "0", "temperature-offset", OPTION_HAS_VALUE, DEVICES_SETTING, JSON_NUMBER, (void *)0, "[0-9]"); - options_add(&alecto_wsd17->options, "0", "show-temperature", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)1, "^[10]{1}$"); - - alecto_wsd17->parseCode=&parseCode; - alecto_wsd17->checkValues=&checkValues; - alecto_wsd17->validate=&validate; - alecto_wsd17->gc=&gc; -} - -#if defined(MODULE) && !defined(_WIN32) -void compatibility(struct module_t *module) { - module->name = "alecto_wsd17"; - module->version = "1.1"; - module->reqversion = "6.0"; - module->reqcommit = "84"; -} - -void init(void) { - alectoWSD17Init(); -} -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/alecto_wsd17.h b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/alecto_wsd17.h deleted file mode 100644 index 3233e44f..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/alecto_wsd17.h +++ /dev/null @@ -1,27 +0,0 @@ -/* - Copyright (C) 2013 CurlyMo - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#ifndef _PROTOCOL_ALECTO_WSD17_H_ -#define _PROTOCOL_ALECTO_WSD17_H_ - -#include "../protocol.h" - -struct protocol_t *alecto_wsd17; -void alectoWSD17Init(void); - -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/alecto_wx500.c b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/alecto_wx500.c deleted file mode 100644 index e7ec2930..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/alecto_wx500.c +++ /dev/null @@ -1,316 +0,0 @@ -/* - Copyright (C) 2014 CurlyMo & Tommybear1979 - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#include -#include -#include -#include - -#include "../../core/pilight.h" -#include "../../core/common.h" -#include "../../core/dso.h" -#include "../../core/log.h" -#include "../protocol.h" -#include "../../core/binary.h" -#include "../../core/gc.h" -#include "alecto_wx500.h" -// -// Protocol characteristics: SYNC bit: 526/8942, Logical 0: 526/1578, Logical 1: 526/3419 -// -#define PULSE_MULTIPLIER 16 -#define MIN_PULSE_LENGTH 235 -#define AVG_PULSE_LENGTH 255 -#define MAX_PULSE_LENGTH 275 -#define ZERO_PULSE 2104 -#define ONE_PULSE 3945 -#define AVG_PULSE (ZERO_PULSE+ONE_PULSE)/2 -#define RAW_LENGTH 74 - -typedef struct settings_t { - double id; - double temp; - double humi; - struct settings_t *next; -} settings_t; - -static struct settings_t *settings = NULL; - -static int validate(void) { - if(alecto_wx500->rawlen == RAW_LENGTH) { - if(alecto_wx500->raw[alecto_wx500->rawlen-1] >= (MIN_PULSE_LENGTH*PULSE_DIV) && - alecto_wx500->raw[alecto_wx500->rawlen-1] <= (MAX_PULSE_LENGTH*PULSE_DIV)) { - return 0; - } - } - return -1; -} - -static void parseCode(void) { - int i = 0, x = 0, type = 0, id = 0, binary[RAW_LENGTH/2]; - double temp_offset = 0.0, humi_offset = 0.0; - double humidity = 0.0, temperature = 0.0; - int winddir = 0, windavg = 0, windgust = 0; - int /*rain = 0, */battery = 0; - int n0 = 0, n1 = 0, n2 = 0, n3 = 0; - int n4 = 0, n5 = 0, n6 = 0, n7 = 0, n8 = 0; - int checksum = 1; - - if(alecto_wx500->rawlen>RAW_LENGTH) { - logprintf(LOG_ERR, "alecto_wx500: parsecode - invalid parameter passed %d", alecto_wx500->rawlen); - return; - } - - for(x=1;xrawlen;x+=2) { - if(alecto_wx500->raw[x] > AVG_PULSE) { - binary[i++] = 1; - } else { - binary[i++] = 0; - } - } - - n8=binToDec(binary, 32, 35); - n7=binToDec(binary, 28, 31); - n6=binToDec(binary, 24, 27); - n5=binToDec(binary, 20, 23); - n4=binToDec(binary, 16, 19); - n3=binToDec(binary, 12, 15); - n2=binToDec(binary, 8, 11); - n1=binToDec(binary, 4, 7); - n0=binToDec(binary, 0, 3); - - struct settings_t *tmp = settings; - while(tmp) { - if(fabs(tmp->id-id) < EPSILON){ - humi_offset = tmp->humi; - temp_offset = tmp->temp; - break; - } - tmp = tmp->next; - } - - if((n2 & 0x6) != 0x6) { - type = 0x1; - checksum = (0xf-n0-n1-n2-n3-n4-n5-n6-n7) & 0xf; - if(n8 != checksum) { - type=0x5; - return; - } - //Wind average * 0.2 - } else if(n3 == 0x1) { - type = 0x2; - checksum = (0xf-n0-n1-n2-n3-n4-n5-n6-n7) & 0xf; - if(n8 != checksum){ - type=0x5; - return; - } - //Wind direction & gust - } else if((n3 & 0x7) == 0x7) { - type = 0x3; - checksum = (0xf-n0-n1-n2-n3-n4-n5-n6-n7) & 0xf; - if(n8 != checksum) { - type=0x5; - return; - } - //Rain - } else if(n3 == 0x3) { - type = 0x4; - checksum = (0x7+n0+n1+n2+n3+n4+n5+n6+n7) & 0xf; - if(n8 != checksum){ - type = 0x5; - return; - } - //Catch - } else { - type = 0x5; - return; - } - - alecto_wx500->message = json_mkobject(); - switch(type) { - case 1: - id = binToDec(binary, 0, 7); - temperature = (double)(binToSigned(binary, 12, 23)) / 10.0; - humidity = (binToDec(binary, 28, 31) * 10) + binToDec(binary, 24,27); - battery = !binary[8]; - - temperature += temp_offset; - humidity += humi_offset; - - json_append_member(alecto_wx500->message, "id", json_mknumber(id, 0)); - json_append_member(alecto_wx500->message, "temperature", json_mknumber(temperature, 1)); - json_append_member(alecto_wx500->message, "humidity", json_mknumber(humidity, 1)); - json_append_member(alecto_wx500->message, "battery", json_mknumber(battery, 0)); - break; - case 2: - id = binToDec(binary, 0, 7); - windavg = binToDec(binary, 24, 31) * 2; - battery = !binary[8]; - - json_append_member(alecto_wx500->message, "id", json_mknumber(id, 0)); - json_append_member(alecto_wx500->message, "windavg", json_mknumber((double)windavg/10, 1)); - json_append_member(alecto_wx500->message, "battery", json_mknumber(battery, 0)); - break; - case 3: - id = binToDec(binary, 0, 7); - winddir = binToDec(binary, 15, 23); - windgust = binToDec(binary, 24, 31) * 2; - battery = !binary[8]; - - json_append_member(alecto_wx500->message, "id", json_mknumber(id, 0)); - json_append_member(alecto_wx500->message, "winddir", json_mknumber((double)winddir, 0)); - json_append_member(alecto_wx500->message, "windgust", json_mknumber((double)windgust/10, 1)); - json_append_member(alecto_wx500->message, "battery", json_mknumber(battery, 0)); - break; - case 4: - id = binToDec(binary, 0, 7); - /*rain = binToDec(binary, 16, 30) * 5;*/ - battery = !binary[8]; - //json_append_member(alecto_wx500->message, "rain", json_mknumber((double)rain/10, 1)); - json_append_member(alecto_wx500->message, "id", json_mknumber(id, 0)); - json_append_member(alecto_wx500->message, "battery", json_mknumber(battery, 0)); - break; - default: - type=0x5; - json_delete(alecto_wx500->message); - alecto_wx500->message = NULL; - return; - break; - } -} - -static int checkValues(struct JsonNode *jvalues) { - struct JsonNode *jid = NULL; - - if((jid = json_find_member(jvalues, "id"))) { - struct settings_t *snode = NULL; - struct JsonNode *jchild = NULL; - struct JsonNode *jchild1 = NULL; - double id = -1; - int match = 0; - - jchild = json_first_child(jid); - while(jchild) { - jchild1 = json_first_child(jchild); - while(jchild1) { - if(strcmp(jchild1->key, "id") == 0) { - id = jchild1->number_; - } - jchild1 = jchild1->next; - } - jchild = jchild->next; - } - - struct settings_t *tmp = settings; - while(tmp) { - if(fabs(tmp->id-id) < EPSILON) { - match = 1; - break; - } - tmp = tmp->next; - } - - if(match == 0) { - if((snode = MALLOC(sizeof(struct settings_t))) == NULL) { - fprintf(stderr, "out of memory\n"); - exit(EXIT_FAILURE); - } - snode->id = id; - snode->temp = 0; - snode->humi = 0; - - json_find_number(jvalues, "temperature-offset", &snode->temp); - json_find_number(jvalues, "humidity-offset", &snode->humi); - - snode->next = settings; - settings = snode; - } - } - return 0; -} - -static void gc(void) { - struct settings_t *tmp = NULL; - while(settings) { - tmp = settings; - settings = settings->next; - FREE(tmp); - } - if(settings != NULL) { - FREE(settings); - } -} - -#if !defined(MODULE) && !defined(_WIN32) -__attribute__((weak)) -#endif -void alectoWX500Init(void) { - - protocol_register(&alecto_wx500); - protocol_set_id(alecto_wx500, "alecto_wx500"); - protocol_device_add(alecto_wx500, "alecto_wx500", "Alecto WX500 Weather Stations"); - protocol_device_add(alecto_wx500, "auriol_h13726", "Auriol H13726 Weather Stations"); - protocol_device_add(alecto_wx500, "ventus_wsxxx", "Ventus WSXXX Weather Stations"); - protocol_device_add(alecto_wx500, "hama_ews1500", "Hama EWS1500 Weather Stations"); - protocol_device_add(alecto_wx500, "meteoscan_w1XX", "Meteoscan W1XXX Weather Stations"); - protocol_device_add(alecto_wx500, "balance_rf_ws105", "Balance RF-WS105 Weather Stations"); - alecto_wx500->devtype = WEATHER; - alecto_wx500->hwtype = RF433; - alecto_wx500->minrawlen = RAW_LENGTH; - alecto_wx500->maxrawlen = RAW_LENGTH; - alecto_wx500->maxgaplen = MAX_PULSE_LENGTH*PULSE_DIV; - alecto_wx500->mingaplen = MIN_PULSE_LENGTH*PULSE_DIV; - - options_add(&alecto_wx500->options, "t", "temperature", OPTION_HAS_VALUE, DEVICES_VALUE, JSON_NUMBER, NULL, "^[0-9]{1,3}$"); - options_add(&alecto_wx500->options, "i", "id", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, "[0-9]"); - options_add(&alecto_wx500->options, "b", "battery", OPTION_HAS_VALUE, DEVICES_VALUE, JSON_NUMBER, NULL, "[0-9]"); - options_add(&alecto_wx500->options, "h", "humidity", OPTION_HAS_VALUE, DEVICES_VALUE, JSON_NUMBER, NULL, "^[0-9]{1,3}$"); - options_add(&alecto_wx500->options, "w", "windavg", OPTION_HAS_VALUE, DEVICES_VALUE, JSON_NUMBER, NULL, "^[0-9]{1,3}$"); - options_add(&alecto_wx500->options, "d", "winddir", OPTION_HAS_VALUE, DEVICES_VALUE, JSON_NUMBER, NULL, "^[0-9]{1,3}$"); - options_add(&alecto_wx500->options, "g", "windgust", OPTION_HAS_VALUE, DEVICES_VALUE, JSON_NUMBER, NULL, "^[0-9]{1,3}$"); - //options_add(&alecto_wx500->options, "r", "rain", OPTION_HAS_VALUE, DEVICES_VALUE, JSON_NUMBER, NULL, "^[0-9]{1,3}$"); - - // options_add(&alecto_wx500->options, "0", "decimals", OPTION_HAS_VALUE, DEVICES_SETTING, JSON_NUMBER, (void *)1, "[0-9]"); - options_add(&alecto_wx500->options, "0", "temperature-decimals", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)1, "[0-9]"); - options_add(&alecto_wx500->options, "0", "humidity-decimals", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)1, "[0-9]"); - options_add(&alecto_wx500->options, "0", "wind-decimals", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)1, "[0-9]"); - options_add(&alecto_wx500->options, "0", "humidity-offset", OPTION_HAS_VALUE, DEVICES_SETTING, JSON_NUMBER, (void *)0, "[0-9]"); - options_add(&alecto_wx500->options, "0", "temperature-offset", OPTION_HAS_VALUE, DEVICES_SETTING, JSON_NUMBER, (void *)0, "[0-9]"); - options_add(&alecto_wx500->options, "0", "show-humidity", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)1, "^[10]{1}$"); - options_add(&alecto_wx500->options, "0", "show-temperature", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)1, "^[10]{1}$"); - options_add(&alecto_wx500->options, "0", "show-battery", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)1, "^[10]{1}$"); - options_add(&alecto_wx500->options, "0", "show-wind", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)1, "^[10]{1}$"); - //options_add(&alecto_wx500->options, "0", "show-rain", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)0, "^[10]{1}$"); - - alecto_wx500->parseCode=&parseCode; - alecto_wx500->checkValues=&checkValues; - alecto_wx500->validate=&validate; - alecto_wx500->gc=&gc; -} - -#ifdef MODULAR -void compatibility(const char **version, const char **commit) { - module->name = "alecto_wx500"; - module->version = "1.2"; - module->reqversion = "6.0"; - module->reqcommit = "84"; -} - -void init(void) { - alectoWX500Init(); -} -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/alecto_wx500.h b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/alecto_wx500.h deleted file mode 100644 index 096f1121..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/alecto_wx500.h +++ /dev/null @@ -1,27 +0,0 @@ -/* - Copyright (C) 2014 CurlyMo & Tommybear1979 - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#ifndef _PROTOCOL_ALECTO_WX500_H_ -#define _PROTOCOL_ALECTO_WX500_H_ - -#include "../protocol.h" - -struct protocol_t *alecto_wx500; -void alectoWX500Init(void); - -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/arctech_contact.c b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/arctech_contact.c deleted file mode 100644 index 47a64034..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/arctech_contact.c +++ /dev/null @@ -1,132 +0,0 @@ -/* - Copyright (C) 2014 CurlyMo & lvdp - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#include -#include -#include -#include - -#include "../../core/pilight.h" -#include "../../core/common.h" -#include "../../core/dso.h" -#include "../../core/log.h" -#include "../protocol.h" -#include "../../core/binary.h" -#include "../../core/gc.h" -#include "arctech_contact.h" - -#define PULSE_MULTIPLIER 4 -#define MIN_PULSE_LENGTH 250 -#define MAX_PULSE_LENGTH 320 -#define AVG_PULSE_LENGTH 300 -#define MIN_RAW_LENGTH 132 -#define MAX_RAW_LENGTH 148 -#define RAW_LENGTH 148 - -static int validate(void) { - if(arctech_contact->rawlen == MIN_RAW_LENGTH || arctech_contact->rawlen == MAX_RAW_LENGTH) { - if(arctech_contact->raw[arctech_contact->rawlen-1] >= (MIN_PULSE_LENGTH*PULSE_DIV) && - arctech_contact->raw[arctech_contact->rawlen-1] <= (MAX_PULSE_LENGTH*PULSE_DIV) && - arctech_contact->raw[1] >= AVG_PULSE_LENGTH*(PULSE_MULTIPLIER*2)) { - return 0; - } - } - - return -1; -} - -static void createMessage(int id, int unit, int state, int all) { - arctech_contact->message = json_mkobject(); - json_append_member(arctech_contact->message, "id", json_mknumber(id, 0)); - if(all == 1) { - json_append_member(arctech_contact->message, "all", json_mknumber(all, 0)); - } else { - json_append_member(arctech_contact->message, "unit", json_mknumber(unit, 0)); - } - - if(state == 1) { - json_append_member(arctech_contact->message, "state", json_mkstring("opened")); - } else { - json_append_member(arctech_contact->message, "state", json_mkstring("closed")); - } -} - -static void parseCode(void) { - int binary[MAX_RAW_LENGTH/4], x = 0, i = 0; - - if(arctech_contact->rawlen>MAX_RAW_LENGTH) { - logprintf(LOG_ERR, "arctech_contact: parsecode - invalid parameter passed %d", arctech_contact->rawlen); - return; - } - - for(x=0;xrawlen;x+=4) { - if(arctech_contact->raw[x+3] > AVG_PULSE_LENGTH*PULSE_MULTIPLIER) { - binary[i++] = 1; - } else { - binary[i++] = 0; - } - } - - int unit = binToDecRev(binary, 28, 31); - int state = binary[27]; - int all = binary[26]; - int id = binToDecRev(binary, 0, 25); - - createMessage(id, unit, state, all); -} - -#if !defined(MODULE) && !defined(_WIN32) -__attribute__((weak)) -#endif -void arctechContactInit(void) { - - protocol_register(&arctech_contact); - protocol_set_id(arctech_contact, "arctech_contact"); - protocol_device_add(arctech_contact, "kaku_contact", "KlikAanKlikUit Contact Sensor"); - protocol_device_add(arctech_contact, "dio_contact", "D-IO Contact Sensor"); - - arctech_contact->devtype = CONTACT; - arctech_contact->hwtype = RF433; - arctech_contact->minrawlen = MIN_RAW_LENGTH; - arctech_contact->maxrawlen = MAX_RAW_LENGTH; - arctech_contact->maxgaplen = MAX_PULSE_LENGTH*PULSE_DIV; - arctech_contact->mingaplen = MIN_PULSE_LENGTH*PULSE_DIV; - - options_add(&arctech_contact->options, "u", "unit", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, "^([0-9]{1}|[1][0-5])$"); - options_add(&arctech_contact->options, "i", "id", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, "^([0-9]{1,7}|[1-5][0-9]{7}|6([0-6][0-9]{6}|7(0[0-9]{5}|10([0-7][0-9]{3}|8([0-7][0-9]{2}|8([0-5][0-9]|6[0-3]))))))$"); - options_add(&arctech_contact->options, "t", "opened", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); - options_add(&arctech_contact->options, "f", "closed", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); - - options_add(&arctech_contact->options, "a", "all", OPTION_HAS_VALUE, DEVICES_SETTING, JSON_NUMBER, (void *)0, "^[10]{1}$"); - - arctech_contact->parseCode=&parseCode; - arctech_contact->validate=&validate; -} - -#if defined(MODULE) && !defined(_WIN32) -void compatibility(struct module_t *module) { - module->name = "arctech_contact"; - module->version = "2.2"; - module->reqversion = "6.0"; - module->reqcommit = "38"; -} - -void init(void) { - arctechContactInit(); -} -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/arctech_contact.h b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/arctech_contact.h deleted file mode 100644 index f37d7396..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/arctech_contact.h +++ /dev/null @@ -1,27 +0,0 @@ -/* - Copyright (C) 2013 CurlyMo & ldvp - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#ifndef _PROTOCOL_ARCTECH_CONTACT_H_ -#define _PROTOCOL_ARCTECH_CONTACT_H_ - -#include "../protocol.h" - -struct protocol_t *arctech_contact; -void arctechContactInit(void); - -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/arctech_dimmer.c b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/arctech_dimmer.c deleted file mode 100644 index d26eae4a..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/arctech_dimmer.c +++ /dev/null @@ -1,363 +0,0 @@ -/* - Copyright (C) 2013 CurlyMo - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#include -#include -#include -#include - -#include "../../core/pilight.h" -#include "../../core/common.h" -#include "../../core/dso.h" -#include "../../core/log.h" -#include "../protocol.h" -#include "../../core/binary.h" -#include "../../core/gc.h" -#include "arctech_dimmer.h" - -#define LEARN_REPEATS 40 -#define NORMAL_REPEATS 10 -#define PULSE_MULTIPLIER 4 -#define MIN_PULSE_LENGTH 250 -#define MAX_PULSE_LENGTH 320 -#define AVG_PULSE_LENGTH 300 -#define MAX_RAW_LENGTH 148 -#define MIN_RAW_LENGTH 132 - -static int validate(void) { - if(arctech_dimmer->rawlen == MAX_RAW_LENGTH || arctech_dimmer->rawlen == MIN_RAW_LENGTH) { - if(arctech_dimmer->raw[arctech_dimmer->rawlen-1] >= (MIN_PULSE_LENGTH*PULSE_DIV) && - arctech_dimmer->raw[arctech_dimmer->rawlen-1] <= (MAX_PULSE_LENGTH*PULSE_DIV) && - arctech_dimmer->raw[1] >= AVG_PULSE_LENGTH*(PULSE_MULTIPLIER*2)) { - return 0; - } - } - - return -1; -} - -static void createMessage(int id, int unit, int state, int all, int dimlevel, int learn) { - arctech_dimmer->message = json_mkobject(); - json_append_member(arctech_dimmer->message, "id", json_mknumber(id, 0)); - - if(all == 1) { - json_append_member(arctech_dimmer->message, "all", json_mknumber(all, 0)); - } else { - json_append_member(arctech_dimmer->message, "unit", json_mknumber(unit, 0)); - } - - /*if(dimlevel == 0) { - state = 0; - } else */if(dimlevel >= 0) { - state = 1; - json_append_member(arctech_dimmer->message, "dimlevel", json_mknumber(dimlevel, 0)); - } - - if(state == 1) { - json_append_member(arctech_dimmer->message, "state", json_mkstring("on")); - } else { - json_append_member(arctech_dimmer->message, "state", json_mkstring("off")); - } - - if(learn == 1) { - arctech_dimmer->txrpt = LEARN_REPEATS; - } else { - arctech_dimmer->txrpt = NORMAL_REPEATS; - } -} - -static void parseCode(void) { - int binary[MAX_RAW_LENGTH/4], x = 0, i = 0; - - if(arctech_dimmer->rawlen>MAX_RAW_LENGTH) { - logprintf(LOG_ERR, "arctech_dimmer: parsecode - invalid parameter passed %d", arctech_dimmer->rawlen); - return; - } - - for(x=0;xrawlen;x+=4) { - if(arctech_dimmer->raw[x+3] > (int)((double)AVG_PULSE_LENGTH*((double)PULSE_MULTIPLIER/2))) { - binary[i++] = 1; - } else { - binary[i++] = 0; - } - } - - int dimlevel = -1; - if(arctech_dimmer->rawlen == MAX_RAW_LENGTH) { - dimlevel = binToDecRev(binary, 32, 35); - } - int unit = binToDecRev(binary, 28, 31); - int state = binary[27]; - int all = binary[26]; - int id = binToDecRev(binary, 0, 25); - - createMessage(id, unit, state, all, dimlevel, 0); -} - -static void createLow(int s, int e) { - int i; - - for(i=s;i<=e;i+=4) { - arctech_dimmer->raw[i]=(AVG_PULSE_LENGTH); - arctech_dimmer->raw[i+1]=(AVG_PULSE_LENGTH); - arctech_dimmer->raw[i+2]=(AVG_PULSE_LENGTH); - arctech_dimmer->raw[i+3]=(AVG_PULSE_LENGTH*PULSE_MULTIPLIER); - } -} - -static void createHigh(int s, int e) { - int i; - - for(i=s;i<=e;i+=4) { - arctech_dimmer->raw[i]=(AVG_PULSE_LENGTH); - arctech_dimmer->raw[i+1]=(AVG_PULSE_LENGTH*PULSE_MULTIPLIER); - arctech_dimmer->raw[i+2]=(AVG_PULSE_LENGTH); - arctech_dimmer->raw[i+3]=(AVG_PULSE_LENGTH); - } -} - -static void clearCode(void) { - createLow(2,147); -} - -static void createStart(void) { - arctech_dimmer->raw[0]=AVG_PULSE_LENGTH; - arctech_dimmer->raw[1]=(10*AVG_PULSE_LENGTH); -} - -static void createId(int id) { - int binary[255]; - int length = 0; - int i=0, x=0; - - length = decToBin(id, binary); - for(i=0;i<=length;i++) { - if(binary[i]==1) { - x=((length-i)+1)*4; - createHigh(106-x, 106-(x-3)); - } - } -} - -static void createAll(int all) { - if(all == 1) { - createHigh(106, 109); - } -} - -static void createState(int state) { - if(state == 1) { - createHigh(110, 113); - } else if(state == -1) { - arctech_dimmer->raw[110]=(AVG_PULSE_LENGTH); - arctech_dimmer->raw[111]=(AVG_PULSE_LENGTH); - arctech_dimmer->raw[112]=(AVG_PULSE_LENGTH); - arctech_dimmer->raw[113]=(AVG_PULSE_LENGTH); - } -} - -static void createUnit(int unit) { - int binary[255]; - int length = 0; - int i=0, x=0; - - length = decToBin(unit, binary); - for(i=0;i<=length;i++) { - if(binary[i]==1) { - x=((length-i)+1)*4; - createHigh(130-x, 130-(x-3)); - } - } -} - -static void createDimlevel(int dimlevel) { - int binary[255]; - int length = 0; - int i=0, x=0; - - length = decToBin(dimlevel, binary); - for(i=0;i<=length;i++) { - if(binary[i]==1) { - x=((length-i)+1)*4; - createHigh(146-x, 146-(x-3)); - } - } -} - -static void createFooter(void) { - arctech_dimmer->raw[arctech_dimmer->rawlen-1]=(PULSE_DIV*AVG_PULSE_LENGTH); -} - -static int checkValues(struct JsonNode *code) { - int dimlevel = -1; - int max = 15; - int min = 0; - double itmp = -1; - - if(json_find_number(code, "dimlevel-maximum", &itmp) == 0) - max = (int)round(itmp); - if(json_find_number(code, "dimlevel-minimum", &itmp) == 0) - min = (int)round(itmp); - if(json_find_number(code, "dimlevel", &itmp) == 0) - dimlevel = (int)round(itmp); - - if(min > max) { - return 1; - } - - if(dimlevel != -1) { - if(dimlevel < min || dimlevel > max) { - return 1; - } else { - return 0; - } - } - return 0; -} - -static int createCode(struct JsonNode *code) { - int id = -1; - int unit = -1; - int state = -1; - int all = 0; - int dimlevel = -1; - int learn = -1; - int max = 15; - int min = 0; - double itmp = -1; - - if(json_find_number(code, "dimlevel-maximum", &itmp) == 0) - max = (int)round(itmp); - if(json_find_number(code, "dimlevel-minimum", &itmp) == 0) - min = (int)round(itmp); - - if(json_find_number(code, "id", &itmp) == 0) - id = (int)round(itmp); - if(json_find_number(code, "unit", &itmp) == 0) - unit = (int)round(itmp); - if(json_find_number(code, "dimlevel", &itmp) == 0) - dimlevel = (int)round(itmp); - if(json_find_number(code, "all", &itmp) == 0) - all = (int)round(itmp); - if(json_find_number(code, "learn", &itmp) == 0) - learn = 1; - - if(json_find_number(code, "off", &itmp) == 0) - state=0; - else if(json_find_number(code, "on", &itmp) == 0) - state=1; - - if(all > 0 && learn > -1) { - logprintf(LOG_ERR, "arctech_dimmer: all and learn cannot be combined"); - return EXIT_FAILURE; - } else if(id == -1 || (unit == -1 && all == 0) || (dimlevel == -1 && state == -1)) { - logprintf(LOG_ERR, "arctech_dimmer: insufficient number of arguments"); - return EXIT_FAILURE; - } else if(id > 67108863 || id < 1) { - logprintf(LOG_ERR, "arctech_dimmer: invalid id range"); - return EXIT_FAILURE; - } else if((unit > 15 || unit < 0) && all == 0) { - logprintf(LOG_ERR, "arctech_dimmer: invalid unit range"); - return EXIT_FAILURE; - } else if(dimlevel != -1 && (dimlevel > max || dimlevel < min) ) { - logprintf(LOG_ERR, "arctech_dimmer: invalid dimlevel range"); - return EXIT_FAILURE; - } else if(dimlevel >= 0 && state == 0) { - logprintf(LOG_ERR, "arctech_dimmer: dimlevel and off state cannot be combined"); - return EXIT_FAILURE; - } else { - if(unit == -1 && all == 1) { - unit = 0; - } - if(dimlevel >= 0) { - state = -1; - } - createMessage(id, unit, state, all, dimlevel, learn); - createStart(); - clearCode(); - createId(id); - createAll(all); - createState(state); - createUnit(unit); - if(dimlevel > -1) { - createDimlevel(dimlevel); - arctech_dimmer->rawlen = MAX_RAW_LENGTH; - } else { - arctech_dimmer->rawlen = MIN_RAW_LENGTH; - } - createFooter(); - } - return EXIT_SUCCESS; -} - -static void printHelp(void) { - printf("\t -u --unit=unit\t\t\tcontrol a device with this unit code\n"); - printf("\t -i --id=id\t\t\tcontrol a device with this id\n"); - printf("\t -a --all\t\t\tsend command to all devices with this id\n"); - printf("\t -d --dimlevel=dimlevel\t\tsend a specific dimlevel\n"); - printf("\t -l --learn\t\t\tsend multiple streams so dimmer can learn\n"); -} - -#if !defined(MODULE) && !defined(_WIN32) -__attribute__((weak)) -#endif -void arctechDimmerInit(void) { - - protocol_register(&arctech_dimmer); - protocol_set_id(arctech_dimmer, "arctech_dimmer"); - protocol_device_add(arctech_dimmer, "kaku_dimmer", "KlikAanKlikUit Dimmers"); - arctech_dimmer->devtype = DIMMER; - arctech_dimmer->hwtype = RF433; - arctech_dimmer->txrpt = NORMAL_REPEATS; - arctech_dimmer->minrawlen = MIN_RAW_LENGTH; - arctech_dimmer->maxrawlen = MAX_RAW_LENGTH; - arctech_dimmer->maxgaplen = MAX_PULSE_LENGTH*PULSE_DIV; - arctech_dimmer->mingaplen = MIN_PULSE_LENGTH*PULSE_DIV; - - options_add(&arctech_dimmer->options, "d", "dimlevel", OPTION_HAS_VALUE, DEVICES_VALUE, JSON_NUMBER, NULL, "^([0-9]{1}|[1][0-5])$"); - options_add(&arctech_dimmer->options, "u", "unit", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, "^([0-9]{1}|[1][0-5])$"); - options_add(&arctech_dimmer->options, "i", "id", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, "^([0-9]{1,7}|[1-5][0-9]{7}|6([0-6][0-9]{6}|7(0[0-9]{5}|10([0-7][0-9]{3}|8([0-7][0-9]{2}|8([0-5][0-9]|6[0-3]))))))$"); - options_add(&arctech_dimmer->options, "t", "on", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); - options_add(&arctech_dimmer->options, "f", "off", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); - options_add(&arctech_dimmer->options, "a", "all", OPTION_OPT_VALUE, DEVICES_OPTIONAL, JSON_NUMBER, NULL, NULL); - options_add(&arctech_dimmer->options, "l", "learn", OPTION_NO_VALUE, DEVICES_OPTIONAL, JSON_NUMBER, NULL, NULL); - - options_add(&arctech_dimmer->options, "0", "dimlevel-minimum", OPTION_HAS_VALUE, DEVICES_SETTING, JSON_NUMBER, (void *)0, "^([0-9]{1}|[1][0-5])$"); - options_add(&arctech_dimmer->options, "0", "dimlevel-maximum", OPTION_HAS_VALUE, DEVICES_SETTING, JSON_NUMBER, (void *)15, "^([0-9]{1}|[1][0-5])$"); - options_add(&arctech_dimmer->options, "0", "readonly", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)0, "^[10]{1}$"); - options_add(&arctech_dimmer->options, "0", "confirm", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)0, "^[10]{1}$"); - - arctech_dimmer->parseCode=&parseCode; - arctech_dimmer->createCode=&createCode; - arctech_dimmer->printHelp=&printHelp; - arctech_dimmer->checkValues=&checkValues; - arctech_dimmer->validate=&validate; -} - -#if defined(MODULE) && !defined(_WIN32) -void compatibility(struct module_t *module) { - module->name = "arctech_dimmer"; - module->version = "3.5"; - module->reqversion = "6.0"; - module->reqcommit = "84"; -} - -void init(void) { - arctechDimmerInit(); -} -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/arctech_dimmer.h b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/arctech_dimmer.h deleted file mode 100644 index 8d10bdac..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/arctech_dimmer.h +++ /dev/null @@ -1,27 +0,0 @@ -/* - Copyright (C) 2013 CurlyMo - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#ifndef _PROTOCOL_ARCTECH_DIMMER_H_ -#define _PROTOCOL_ARCTECH_DIMMER_H_ - -#include "../protocol.h" - -struct protocol_t *arctech_dimmer; -void arctechDimmerInit(void); - -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/arctech_dusk.c b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/arctech_dusk.c deleted file mode 100644 index a173b7df..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/arctech_dusk.c +++ /dev/null @@ -1,125 +0,0 @@ -/* - Copyright (C) 2014 CurlyMo & lvdp - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#include -#include -#include - -#include "../../core/pilight.h" -#include "../../core/common.h" -#include "../../core/dso.h" -#include "../../core/log.h" -#include "../protocol.h" -#include "../../core/binary.h" -#include "../../core/gc.h" -#include "arctech_dusk.h" - -#define PULSE_MULTIPLIER 3 -#define MIN_PULSE_LENGTH 250 -#define MAX_PULSE_LENGTH 282 -#define AVG_PULSE_LENGTH 277 -#define RAW_LENGTH 132 - -static int validate(void) { - if(arctech_dusk->rawlen == RAW_LENGTH) { - if(arctech_dusk->raw[arctech_dusk->rawlen-1] >= (MIN_PULSE_LENGTH*PULSE_DIV) && - arctech_dusk->raw[arctech_dusk->rawlen-1] <= (MAX_PULSE_LENGTH*PULSE_DIV) && - arctech_dusk->raw[1] >= AVG_PULSE_LENGTH*(PULSE_MULTIPLIER*3)) { - return 0; - } - } - - return -1; -} - -static void createMessage(int id, int unit, int state, int all) { - arctech_dusk->message = json_mkobject(); - json_append_member(arctech_dusk->message, "id", json_mknumber(id, 0)); - if(all == 1) { - json_append_member(arctech_dusk->message, "all", json_mknumber(all, 0)); - } else { - json_append_member(arctech_dusk->message, "unit", json_mknumber(unit, 0)); - } - - if(state == 1) { - json_append_member(arctech_dusk->message, "state", json_mkstring("dusk")); - } else { - json_append_member(arctech_dusk->message, "state", json_mkstring("dawn")); - } -} - -static void parseCode(void) { - int binary[RAW_LENGTH/4], x = 0, i = 0; - - if(arctech_dusk->rawlen>RAW_LENGTH) { - logprintf(LOG_ERR, "arctech_dusk: parsecode - invalid parameter passed %d", arctech_dusk->rawlen); - return; - } - - for(x=0;xrawlen;x+=4) { - if(arctech_dusk->raw[x+3] > AVG_PULSE_LENGTH*PULSE_MULTIPLIER) { - binary[i++] = 1; - } else { - binary[i++] = 0; - } - } - - int unit = binToDecRev(binary, 28, 31); - int state = binary[27]; - int all = binary[26]; - int id = binToDecRev(binary, 0, 25); - - createMessage(id, unit, state, all); -} - -#if !defined(MODULE) && !defined(_WIN32) -__attribute__((weak)) -#endif -void arctechDuskInit(void) { - - protocol_register(&arctech_dusk); - protocol_set_id(arctech_dusk, "arctech_dusk"); - protocol_device_add(arctech_dusk, "kaku_dusk", "KlikAanKlikUit Dusk Sensor"); - arctech_dusk->devtype = DUSK; - arctech_dusk->hwtype = RF433; - arctech_dusk->minrawlen = RAW_LENGTH; - arctech_dusk->maxrawlen = RAW_LENGTH; - arctech_dusk->maxgaplen = MAX_PULSE_LENGTH*PULSE_DIV; - arctech_dusk->mingaplen = MIN_PULSE_LENGTH*PULSE_DIV; - - options_add(&arctech_dusk->options, "u", "unit", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, "^([0-9]{1}|[1][0-5])$"); - options_add(&arctech_dusk->options, "i", "id", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, "^([0-9]{1,7}|[1-5][0-9]{7}|6([0-6][0-9]{6}|7(0[0-9]{5}|10([0-7][0-9]{3}|8([0-7][0-9]{2}|8([0-5][0-9]|6[0-3]))))))$"); - options_add(&arctech_dusk->options, "t", "dusk", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); - options_add(&arctech_dusk->options, "f", "dawn", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); - - arctech_dusk->parseCode=&parseCode; - arctech_dusk->validate=&validate; -} - -#if defined(MODULE) && !defined(_WIN32) -void compatibility(struct module_t *module) { - module->name = "arctech_dusk"; - module->version = "2.2"; - module->reqversion = "6.0"; - module->reqcommit = "84"; -} - -void init(void) { - arctechDuskInit(); -} -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/arctech_dusk.h b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/arctech_dusk.h deleted file mode 100644 index 5fa32754..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/arctech_dusk.h +++ /dev/null @@ -1,27 +0,0 @@ -/* - Copyright (C) 2013 CurlyMo & ldvp - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#ifndef _PROTOCOL_ARCTECH_DUSK_H_ -#define _PROTOCOL_ARCTECH_DUSK_H_ - -#include "../protocol.h" - -struct protocol_t *arctech_dusk; -void arctechDuskInit(void); - -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/arctech_motion.c b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/arctech_motion.c deleted file mode 100644 index 82b95d4c..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/arctech_motion.c +++ /dev/null @@ -1,125 +0,0 @@ -/* - Copyright (C) 2014 CurlyMo & lvdp - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#include -#include -#include - -#include "../../core/pilight.h" -#include "../../core/common.h" -#include "../../core/dso.h" -#include "../../core/log.h" -#include "../protocol.h" -#include "../../core/binary.h" -#include "../../core/gc.h" -#include "arctech_motion.h" - -#define PULSE_MULTIPLIER 3 -#define MIN_PULSE_LENGTH 250 -#define MAX_PULSE_LENGTH 284 -#define AVG_PULSE_LENGTH 279 -#define RAW_LENGTH 132 - -static int validate(void) { - if(arctech_motion->rawlen == RAW_LENGTH) { - if(arctech_motion->raw[arctech_motion->rawlen-1] >= (MIN_PULSE_LENGTH*PULSE_DIV) && - arctech_motion->raw[arctech_motion->rawlen-1] <= (MAX_PULSE_LENGTH*PULSE_DIV) && - arctech_motion->raw[1] >= AVG_PULSE_LENGTH*(PULSE_MULTIPLIER*3)) { - return 0; - } - } - - return -1; -} - -static void createMessage(int id, int unit, int state, int all) { - arctech_motion->message = json_mkobject(); - json_append_member(arctech_motion->message, "id", json_mknumber(id, 0)); - if(all == 1) { - json_append_member(arctech_motion->message, "all", json_mknumber(all, 0)); - } else { - json_append_member(arctech_motion->message, "unit", json_mknumber(unit, 0)); - } - - if(state == 1) { - json_append_member(arctech_motion->message, "state", json_mkstring("on")); - } else { - json_append_member(arctech_motion->message, "state", json_mkstring("off")); - } -} - -static void parseCode(void) { - int binary[RAW_LENGTH/4], x = 0, i = 0; - - if(arctech_motion->rawlen>RAW_LENGTH) { - logprintf(LOG_ERR, "arctech_motion: parsecode - invalid parameter passed %d", arctech_motion->rawlen); - return; - } - - for(x=0;xrawlen;x+=4) { - if(arctech_motion->raw[x+3] > AVG_PULSE_LENGTH*PULSE_MULTIPLIER) { - binary[i++] = 1; - } else { - binary[i++] = 0; - } - } - - int unit = binToDecRev(binary, 28, 31); - int state = binary[27]; - int all = binary[26]; - int id = binToDecRev(binary, 0, 25); - - createMessage(id, unit, state, all); -} - -#if !defined(MODULE) && !defined(_WIN32) -__attribute__((weak)) -#endif -void arctechMotionInit(void) { - - protocol_register(&arctech_motion); - protocol_set_id(arctech_motion, "arctech_motion"); - protocol_device_add(arctech_motion, "kaku_motion", "KlikAanKlikUit Motion Sensor"); - arctech_motion->devtype = MOTION; - arctech_motion->hwtype = RF433; - arctech_motion->minrawlen = RAW_LENGTH; - arctech_motion->maxrawlen = RAW_LENGTH; - arctech_motion->maxgaplen = MAX_PULSE_LENGTH*PULSE_DIV; - arctech_motion->mingaplen = MIN_PULSE_LENGTH*PULSE_DIV; - - options_add(&arctech_motion->options, "u", "unit", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, "^([0-9]{1}|[1][0-5])$"); - options_add(&arctech_motion->options, "i", "id", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, "^([0-9]{1,7}|[1-5][0-9]{7}|6([0-6][0-9]{6}|7(0[0-9]{5}|10([0-7][0-9]{3}|8([0-7][0-9]{2}|8([0-5][0-9]|6[0-3]))))))$"); - options_add(&arctech_motion->options, "t", "on", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); - options_add(&arctech_motion->options, "f", "off", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); - - arctech_motion->parseCode=&parseCode; - arctech_motion->validate=&validate; -} - -#if defined(MODULE) && !defined(_WIN32) -void compatibility(struct module_t *module) { - module->name = "arctech_motion"; - module->version = "2.2"; - module->reqversion = "6.0"; - module->reqcommit = "84"; -} - -void init(void) { - arctechMotionInit(); -} -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/arctech_motion.h b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/arctech_motion.h deleted file mode 100644 index 67c59e5d..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/arctech_motion.h +++ /dev/null @@ -1,27 +0,0 @@ -/* - Copyright (C) 2013 CurlyMo & lvdp - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#ifndef _PROTOCOL_ARCTECH_MOTION_H_ -#define _PROTOCOL_ARCTECH_MOTION_H_ - -#include "../protocol.h" - -struct protocol_t *arctech_motion; -void arctechMotionInit(void); - -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/arctech_screen.c b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/arctech_screen.c deleted file mode 100644 index 21c8f24b..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/arctech_screen.c +++ /dev/null @@ -1,277 +0,0 @@ -/* - Copyright (C) 2013 CurlyMo - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#include -#include -#include -#include - -#include "../../core/pilight.h" -#include "../../core/common.h" -#include "../../core/dso.h" -#include "../../core/log.h" -#include "../protocol.h" -#include "../../core/binary.h" -#include "../../core/gc.h" -#include "arctech_screen.h" - -#define LEARN_REPEATS 40 -#define NORMAL_REPEATS 10 -#define PULSE_MULTIPLIER 5 -#define MIN_PULSE_LENGTH 250 -#define MAX_PULSE_LENGTH 320 -#define AVG_PULSE_LENGTH 300 -#define RAW_LENGTH 132 - -static int validate(void) { - if(arctech_screen->rawlen == RAW_LENGTH) { - if(arctech_screen->raw[arctech_screen->rawlen-1] >= (MIN_PULSE_LENGTH*PULSE_DIV) && - arctech_screen->raw[arctech_screen->rawlen-1] <= (MAX_PULSE_LENGTH*PULSE_DIV) && - arctech_screen->raw[1] >= AVG_PULSE_LENGTH*(PULSE_MULTIPLIER*1.5)) { - return 0; - } - } - - return -1; -} - -static void createMessage(int id, int unit, int state, int all, int learn) { - arctech_screen->message = json_mkobject(); - json_append_member(arctech_screen->message, "id", json_mknumber(id, 0)); - if(all == 1) { - json_append_member(arctech_screen->message, "all", json_mknumber(all, 0)); - } else { - json_append_member(arctech_screen->message, "unit", json_mknumber(unit, 0)); - } - - if(state == 1) { - json_append_member(arctech_screen->message, "state", json_mkstring("up")); - } else { - json_append_member(arctech_screen->message, "state", json_mkstring("down")); - } - - if(learn == 1) { - arctech_screen->txrpt = LEARN_REPEATS; - } else { - arctech_screen->txrpt = NORMAL_REPEATS; - } -} - -static void parseCode(void) { - int binary[RAW_LENGTH/4], x = 0, i = 0; - - if(arctech_screen->rawlen>RAW_LENGTH) { - logprintf(LOG_ERR, "arctech_screen: parsecode - invalid parameter passed %d", arctech_screen->rawlen); - return; - } - - for(x=0;xrawlen;x+=4) { - if(arctech_screen->raw[x+3] > (int)((double)AVG_PULSE_LENGTH*((double)PULSE_MULTIPLIER/2))) { - binary[i++] = 1; - } else { - binary[i++] = 0; - } - } - - int unit = binToDecRev(binary, 28, 31); - int state = binary[27]; - int all = binary[26]; - int id = binToDecRev(binary, 0, 25); - - createMessage(id, unit, state, all, 0); -} - -static void createLow(int s, int e) { - int i; - - for(i=s;i<=e;i+=4) { - arctech_screen->raw[i]=(AVG_PULSE_LENGTH); - arctech_screen->raw[i+1]=(AVG_PULSE_LENGTH); - arctech_screen->raw[i+2]=(AVG_PULSE_LENGTH); - arctech_screen->raw[i+3]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - } -} - -static void createHigh(int s, int e) { - int i; - - for(i=s;i<=e;i+=4) { - arctech_screen->raw[i]=(AVG_PULSE_LENGTH); - arctech_screen->raw[i+1]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - arctech_screen->raw[i+2]=(AVG_PULSE_LENGTH); - arctech_screen->raw[i+3]=(AVG_PULSE_LENGTH); - } -} - -static void clearCode(void) { - createLow(2, 132); -} - -static void createStart(void) { - arctech_screen->raw[0]=(AVG_PULSE_LENGTH); - arctech_screen->raw[1]=(9*AVG_PULSE_LENGTH); -} - -static void createId(int id) { - int binary[255]; - int length = 0; - int i=0, x=0; - - length = decToBin(id, binary); - for(i=0;i<=length;i++) { - if(binary[i]==1) { - x=((length-i)+1)*4; - createHigh(106-x, 106-(x-3)); - } - } -} - -static void createAll(int all) { - if(all == 1) { - createHigh(106, 109); - } -} - -static void createState(int state) { - if(state == 1) { - createHigh(110, 113); - } -} - -static void createUnit(int unit) { - int binary[255]; - int length = 0; - int i=0, x=0; - - length = decToBin(unit, binary); - for(i=0;i<=length;i++) { - if(binary[i]==1) { - x=((length-i)+1)*4; - createHigh(130-x, 130-(x-3)); - } - } -} - -static void createFooter(void) { - arctech_screen->raw[131]=(PULSE_DIV*AVG_PULSE_LENGTH); -} - -static int createCode(struct JsonNode *code) { - int id = -1; - int unit = -1; - int state = -1; - int all = 0; - int learn = -1; - double itmp = -1; - - if(json_find_number(code, "id", &itmp) == 0) - id = (int)round(itmp); - if(json_find_number(code, "unit", &itmp) == 0) - unit = (int)round(itmp); - if(json_find_number(code, "all", &itmp) == 0) - all = (int)round(itmp); - if(json_find_number(code, "down", &itmp) == 0) - state=0; - else if(json_find_number(code, "up", &itmp) == 0) - state=1; - if(json_find_number(code, "learn", &itmp) == 0) - learn = 1; - - if(all > 0 && learn > -1) { - logprintf(LOG_ERR, "arctech_screen: all and learn cannot be combined"); - return EXIT_FAILURE; - } else if(id == -1 || (unit == -1 && all == 0) || state == -1) { - logprintf(LOG_ERR, "arctech_screen: insufficient number of arguments"); - return EXIT_FAILURE; - } else if(id > 67108863 || id < 1) { - logprintf(LOG_ERR, "arctech_screen: invalid id range"); - return EXIT_FAILURE; - } else if((unit > 15 || unit < 0) && all == 0) { - logprintf(LOG_ERR, "arctech_screen: invalid unit range"); - return EXIT_FAILURE; - } else { - if(unit == -1 && all == 1) { - unit = 0; - } - createMessage(id, unit, state, all, learn); - createStart(); - clearCode(); - createId(id); - createAll(all); - createState(state); - createUnit(unit); - createFooter(); - arctech_screen->rawlen = RAW_LENGTH; - } - return EXIT_SUCCESS; -} - -static void printHelp(void) { - printf("\t -t --up\t\t\tsend an up signal\n"); - printf("\t -f --down\t\t\tsend an down signal\n"); - printf("\t -u --unit=unit\t\t\tcontrol a device with this unit code\n"); - printf("\t -i --id=id\t\t\tcontrol a device with this id\n"); - printf("\t -a --all\t\t\tsend command to all devices with this id\n"); - printf("\t -l --learn\t\t\tsend multiple streams so screen can learn\n"); -} - -#if !defined(MODULE) && !defined(_WIN32) -__attribute__((weak)) -#endif -void arctechScreenInit(void) { - - protocol_register(&arctech_screen); - protocol_set_id(arctech_screen, "arctech_screen"); - protocol_device_add(arctech_screen, "kaku_screen", "KlikAanKlikUit Screens"); - protocol_device_add(arctech_screen, "dio_screen", "DI-O Screens"); - arctech_screen->devtype = SCREEN; - arctech_screen->hwtype = RF433; - arctech_screen->txrpt = NORMAL_REPEATS; - arctech_screen->minrawlen = RAW_LENGTH; - arctech_screen->maxrawlen = RAW_LENGTH; - arctech_screen->maxgaplen = MAX_PULSE_LENGTH*PULSE_DIV; - arctech_screen->mingaplen = MIN_PULSE_LENGTH*PULSE_DIV; - - options_add(&arctech_screen->options, "t", "up", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); - options_add(&arctech_screen->options, "f", "down", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); - options_add(&arctech_screen->options, "u", "unit", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, "^([0-9]{1}|[1][0-5])$"); - options_add(&arctech_screen->options, "i", "id", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, "^([0-9]{1,7}|[1-5][0-9]{7}|6([0-6][0-9]{6}|7(0[0-9]{5}|10([0-7][0-9]{3}|8([0-7][0-9]{2}|8([0-5][0-9]|6[0-3]))))))$"); - options_add(&arctech_screen->options, "a", "all", OPTION_OPT_VALUE, DEVICES_OPTIONAL, JSON_NUMBER, NULL, NULL); - options_add(&arctech_screen->options, "l", "learn", OPTION_NO_VALUE, DEVICES_OPTIONAL, JSON_NUMBER, NULL, NULL); - - options_add(&arctech_screen->options, "0", "readonly", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)0, "^[10]{1}$"); - options_add(&arctech_screen->options, "0", "confirm", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)0, "^[10]{1}$"); - - arctech_screen->parseCode=&parseCode; - arctech_screen->createCode=&createCode; - arctech_screen->printHelp=&printHelp; - arctech_screen->validate=&validate; -} - -#if defined(MODULE) && !defined(_WIN32) -void compatibility(struct module_t *module) { - module->name = "arctech_screen"; - module->version = "3.4"; - module->reqversion = "6.0"; - module->reqcommit = "84"; -} - -void init(void) { - arctechScreenInit(); -} -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/arctech_screen.h b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/arctech_screen.h deleted file mode 100644 index c9b790af..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/arctech_screen.h +++ /dev/null @@ -1,27 +0,0 @@ -/* - Copyright (C) 2013 CurlyMo - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#ifndef _PROTOCOL_ARCTECH_SCREEN_H_ -#define _PROTOCOL_ARCTECH_SCREEN_H_ - -#include "../protocol.h" - -struct protocol_t *arctech_screen; -void arctechScreenInit(void); - -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/arctech_screen_old.c b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/arctech_screen_old.c deleted file mode 100644 index 6ebb8ef2..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/arctech_screen_old.c +++ /dev/null @@ -1,232 +0,0 @@ -/* - Copyright (C) 2013 CurlyMo - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#include -#include -#include -#include - -#include "../../core/pilight.h" -#include "../../core/common.h" -#include "../../core/dso.h" -#include "../../core/log.h" -#include "../protocol.h" -#include "../../core/binary.h" -#include "../../core/gc.h" -#include "arctech_screen_old.h" - -#define PULSE_MULTIPLIER 3 -#define MIN_PULSE_LENGTH 310 -#define MAX_PULSE_LENGTH 350 -#define AVG_PULSE_LENGTH 335 -#define RAW_LENGTH 50 - -static int validate(void) { - if(arctech_screen_old->rawlen == RAW_LENGTH) { - if(arctech_screen_old->raw[arctech_screen_old->rawlen-1] >= (MIN_PULSE_LENGTH*PULSE_DIV) && - arctech_screen_old->raw[arctech_screen_old->rawlen-1] <= (MAX_PULSE_LENGTH*PULSE_DIV)) { - return 0; - } - } - - return -1; -} - -static void createMessage(int id, int unit, int state) { - arctech_screen_old->message = json_mkobject(); - json_append_member(arctech_screen_old->message, "id", json_mknumber(id, 0)); - json_append_member(arctech_screen_old->message, "unit", json_mknumber(unit, 0)); - if(state == 1) - json_append_member(arctech_screen_old->message, "state", json_mkstring("up")); - else - json_append_member(arctech_screen_old->message, "state", json_mkstring("down")); -} - -static void parseCode(void) { - int binary[RAW_LENGTH/4], x = 0, i = 0; - int len = (int)((double)AVG_PULSE_LENGTH*((double)PULSE_MULTIPLIER/2)); - - if(arctech_screen_old->rawlen>RAW_LENGTH) { - logprintf(LOG_ERR, "arctech_screen_old: parsecode - invalid parameter passed %d", arctech_screen_old->rawlen); - return; - } - - for(x=0;xrawlen-2;x+=4) { - if(arctech_screen_old->raw[x+3] > len) { - binary[i++] = 0; - } else { - binary[i++] = 1; - } - } - - int unit = binToDec(binary, 0, 3); - int state = binary[11]; - int id = binToDec(binary, 4, 8); - createMessage(id, unit, state); -} - -static void createLow(int s, int e) { - int i; - - for(i=s;i<=e;i+=4) { - arctech_screen_old->raw[i]=(AVG_PULSE_LENGTH); - arctech_screen_old->raw[i+1]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - arctech_screen_old->raw[i+2]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - arctech_screen_old->raw[i+3]=(AVG_PULSE_LENGTH); - } -} - -static void createHigh(int s, int e) { - int i; - - for(i=s;i<=e;i+=4) { - arctech_screen_old->raw[i]=(AVG_PULSE_LENGTH); - arctech_screen_old->raw[i+1]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - arctech_screen_old->raw[i+2]=(AVG_PULSE_LENGTH); - arctech_screen_old->raw[i+3]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - } -} - -static void clearCode(void) { - createHigh(0,35); - createLow(36,47); -} - -static void createUnit(int unit) { - int binary[255]; - int length = 0; - int i=0, x=0; - - length = decToBinRev(unit, binary); - for(i=0;i<=length;i++) { - if(binary[i]==1) { - x=i*4; - createLow(x, x+3); - } - } -} - -static void createId(int id) { - int binary[255]; - int length = 0; - int i=0, x=0; - - length = decToBinRev(id, binary); - for(i=0;i<=length;i++) { - if(binary[i]==1) { - x=i*4; - createLow(16+x, 16+x+3); - } - } -} - -static void createState(int state) { - if(state == 0) { - createHigh(44,47); - } -} - -static void createFooter(void) { - arctech_screen_old->raw[48]=(AVG_PULSE_LENGTH); - arctech_screen_old->raw[49]=(PULSE_DIV*AVG_PULSE_LENGTH); -} - -static int createCode(struct JsonNode *code) { - int id = -1; - int unit = -1; - int state = -1; - double itmp = -1; - - if(json_find_number(code, "id", &itmp) == 0) - id = (int)round(itmp); - if(json_find_number(code, "unit", &itmp) == 0) - unit = (int)round(itmp); - if(json_find_number(code, "down", &itmp) == 0) - state=0; - else if(json_find_number(code, "up", &itmp) == 0) - state=1; - - if(id == -1 || unit == -1 || state == -1) { - logprintf(LOG_ERR, "arctech_screen_old: insufficient number of arguments"); - return EXIT_FAILURE; - } else if(id > 31 || id < 0) { - logprintf(LOG_ERR, "arctech_screen_old: invalid id range"); - return EXIT_FAILURE; - } else if(unit > 15 || unit < 0) { - logprintf(LOG_ERR, "arctech_screen_old: invalid unit range"); - return EXIT_FAILURE; - } else { - createMessage(id, unit, state); - clearCode(); - createUnit(unit); - createId(id); - createState(state); - createFooter(); - arctech_screen_old->rawlen = RAW_LENGTH; - } - return EXIT_SUCCESS; -} - -static void printHelp(void) { - printf("\t -t --up\t\t\tsend an up signal\n"); - printf("\t -f --down\t\t\tsend an down signal\n"); - printf("\t -u --unit=unit\t\t\tcontrol a device with this unit code\n"); - printf("\t -i --id=id\t\t\tcontrol a device with this id\n"); -} - -#if !defined(MODULE) && !defined(_WIN32) -__attribute__((weak)) -#endif -void arctechScreenOldInit(void) { - - protocol_register(&arctech_screen_old); - protocol_set_id(arctech_screen_old, "arctech_screen_old"); - protocol_device_add(arctech_screen_old, "kaku_screen_old", "Old KlikAanKlikUit Screens"); - arctech_screen_old->devtype = SCREEN; - arctech_screen_old->hwtype = RF433; - arctech_screen_old->minrawlen = RAW_LENGTH; - arctech_screen_old->maxrawlen = RAW_LENGTH; - arctech_screen_old->maxgaplen = MAX_PULSE_LENGTH*PULSE_DIV; - arctech_screen_old->mingaplen = MIN_PULSE_LENGTH*PULSE_DIV; - - options_add(&arctech_screen_old->options, "t", "up", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); - options_add(&arctech_screen_old->options, "f", "down", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); - options_add(&arctech_screen_old->options, "u", "unit", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, "^([0-9]{1}|[1][0-5])$"); - options_add(&arctech_screen_old->options, "i", "id", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, "^(3[012]?|[012][0-9]|[0-9]{1})$"); - - options_add(&arctech_screen_old->options, "0", "readonly", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)0, "^[10]{1}$"); - options_add(&arctech_screen_old->options, "0", "confirm", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)0, "^[10]{1}$"); - - arctech_screen_old->parseCode=&parseCode; - arctech_screen_old->createCode=&createCode; - arctech_screen_old->printHelp=&printHelp; - arctech_screen_old->validate=&validate; -} - -#if defined(MODULE) && !defined(_WIN32) -void compatibility(struct module_t *module) { - module->name = "arctech_screen_old"; - module->version = "2.5"; - module->reqversion = "6.0"; - module->reqcommit = "84"; -} - -void init(void) { - arctechScreenOldInit(); -} -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/arctech_screen_old.h b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/arctech_screen_old.h deleted file mode 100644 index 09080dc8..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/arctech_screen_old.h +++ /dev/null @@ -1,27 +0,0 @@ -/* - Copyright (C) 2013 CurlyMo - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#ifndef _PROTOCOL_ARCTECH_SCREEN_OLD_H_ -#define _PROTOCOL_ARCTECH_SCREEN_OLD_H_ - -#include "../protocol.h" - -struct protocol_t *arctech_screen_old; -void arctechScreenOldInit(void); - -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/arctech_switch.c b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/arctech_switch.c deleted file mode 100644 index 7bddf711..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/arctech_switch.c +++ /dev/null @@ -1,281 +0,0 @@ -/* - Copyright (C) 2013 CurlyMo - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#include -#include -#include -#include - -#include "../../core/pilight.h" -#include "../../core/common.h" -#include "../../core/dso.h" -#include "../../core/log.h" -#include "../protocol.h" -#include "../../core/binary.h" -#include "../../core/gc.h" -#include "arctech_switch.h" - -#define LEARN_REPEATS 40 -#define NORMAL_REPEATS 10 -#define PULSE_MULTIPLIER 4 -#define MIN_PULSE_LENGTH 250 -#define MAX_PULSE_LENGTH 320 -#define AVG_PULSE_LENGTH 315 -#define RAW_LENGTH 132 - -static int validate(void) { - if(arctech_switch->rawlen == RAW_LENGTH) { - if(arctech_switch->raw[arctech_switch->rawlen-1] >= (MIN_PULSE_LENGTH*PULSE_DIV) && - arctech_switch->raw[arctech_switch->rawlen-1] <= (MAX_PULSE_LENGTH*PULSE_DIV) && - arctech_switch->raw[1] >= AVG_PULSE_LENGTH*(PULSE_MULTIPLIER*1.5)) { - return 0; - } - } - - return -1; -} - -static void createMessage(int id, int unit, int state, int all, int learn) { - arctech_switch->message = json_mkobject(); - - json_append_member(arctech_switch->message, "id", json_mknumber(id, 0)); - - if(all == 1) { - json_append_member(arctech_switch->message, "all", json_mknumber(all, 0)); - } else { - json_append_member(arctech_switch->message, "unit", json_mknumber(unit, 0)); - } - - if(state == 1) { - json_append_member(arctech_switch->message, "state", json_mkstring("on")); - } else { - json_append_member(arctech_switch->message, "state", json_mkstring("off")); - } - - if(learn == 1) { - arctech_switch->txrpt = LEARN_REPEATS; - } else { - arctech_switch->txrpt = NORMAL_REPEATS; - } -} - -static void parseCode(void) { - int binary[RAW_LENGTH/4], x = 0, i = 0; - - if(arctech_switch->rawlen>RAW_LENGTH) { - logprintf(LOG_ERR, "arctech_switch: parsecode - invalid parameter passed %d", arctech_switch->rawlen); - return; - } - - for(x=0;xrawlen;x+=4) { - if(arctech_switch->raw[x+3] > (int)((double)AVG_PULSE_LENGTH*((double)PULSE_MULTIPLIER/2))) { - binary[i++] = 1; - } else { - binary[i++] = 0; - } - } - - int unit = binToDecRev(binary, 28, 31); - int state = binary[27]; - int all = binary[26]; - int id = binToDecRev(binary, 0, 25); - - createMessage(id, unit, state, all, 0); -} - -static void createLow(int s, int e) { - int i; - - for(i=s;i<=e;i+=4) { - arctech_switch->raw[i]=(AVG_PULSE_LENGTH); - arctech_switch->raw[i+1]=(AVG_PULSE_LENGTH); - arctech_switch->raw[i+2]=(AVG_PULSE_LENGTH); - arctech_switch->raw[i+3]=(AVG_PULSE_LENGTH*PULSE_MULTIPLIER); - } -} - -static void createHigh(int s, int e) { - int i; - - for(i=s;i<=e;i+=4) { - arctech_switch->raw[i]=(AVG_PULSE_LENGTH); - arctech_switch->raw[i+1]=(AVG_PULSE_LENGTH*PULSE_MULTIPLIER); - arctech_switch->raw[i+2]=(AVG_PULSE_LENGTH); - arctech_switch->raw[i+3]=(AVG_PULSE_LENGTH); - } -} - -static void clearCode(void) { - createLow(2, 131); -} - -static void createStart(void) { - arctech_switch->raw[0]=(AVG_PULSE_LENGTH); - arctech_switch->raw[1]=(9*AVG_PULSE_LENGTH); -} - -static void createId(int id) { - int binary[255]; - int length = 0; - int i=0, x=0; - - length = decToBin(id, binary); - for(i=0;i<=length;i++) { - if(binary[i]==1) { - x=((length-i)+1)*4; - createHigh(106-x, 106-(x-3)); - } - } -} - -static void createAll(int all) { - if(all == 1) { - createHigh(106, 109); - } -} - -static void createState(int state) { - if(state == 1) { - createHigh(110, 113); - } -} - -static void createUnit(int unit) { - int binary[255]; - int length = 0; - int i=0, x=0; - - length = decToBin(unit, binary); - for(i=0;i<=length;i++) { - if(binary[i]==1) { - x=((length-i)+1)*4; - createHigh(130-x, 130-(x-3)); - } - } -} - -static void createFooter(void) { - arctech_switch->raw[131]=(PULSE_DIV*AVG_PULSE_LENGTH); -} - -static int createCode(struct JsonNode *code) { - int id = -1; - int unit = -1; - int state = -1; - int all = 0; - int learn = -1; - double itmp = -1; - - if(json_find_number(code, "id", &itmp) == 0) - id = (int)round(itmp); - if(json_find_number(code, "unit", &itmp) == 0) - unit = (int)round(itmp); - if(json_find_number(code, "all", &itmp) == 0) - all = (int)round(itmp); - if(json_find_number(code, "off", &itmp) == 0) - state=0; - else if(json_find_number(code, "on", &itmp) == 0) - state=1; - if(json_find_number(code, "learn", &itmp) == 0) - learn = 1; - - if(all > 0 && learn > -1) { - logprintf(LOG_ERR, "arctech_switch: all and learn cannot be combined"); - return EXIT_FAILURE; - } else if(id == -1 || (unit == -1 && all == 0) || state == -1) { - logprintf(LOG_ERR, "arctech_switch: insufficient number of arguments"); - return EXIT_FAILURE; - } else if(id > 67108863 || id < 1) { - logprintf(LOG_ERR, "arctech_switch: invalid id range"); - return EXIT_FAILURE; - } else if((unit > 15 || unit < 0) && all == 0) { - logprintf(LOG_ERR, "arctech_switch: invalid unit range"); - return EXIT_FAILURE; - } else { - if(unit == -1 && all == 1) { - unit = 0; - } - createMessage(id, unit, state, all, learn); - createStart(); - clearCode(); - createId(id); - createAll(all); - createState(state); - createUnit(unit); - createFooter(); - arctech_switch->rawlen = RAW_LENGTH; - } - return EXIT_SUCCESS; -} - -static void printHelp(void) { - printf("\t -t --on\t\t\tsend an on signal\n"); - printf("\t -f --off\t\t\tsend an off signal\n"); - printf("\t -u --unit=unit\t\t\tcontrol a device with this unit code\n"); - printf("\t -i --id=id\t\t\tcontrol a device with this id\n"); - printf("\t -a --all\t\t\tsend command to all devices with this id\n"); - printf("\t -l --learn\t\t\tsend multiple streams so switch can learn\n"); -} - -#if !defined(MODULE) && !defined(_WIN32) -__attribute__((weak)) -#endif -void arctechSwitchInit(void) { - protocol_register(&arctech_switch); - protocol_set_id(arctech_switch, "arctech_switch"); - protocol_device_add(arctech_switch, "kaku_switch", "KlikAanKlikUit Switches"); - protocol_device_add(arctech_switch, "dio_switch", "D-IO Switches"); - protocol_device_add(arctech_switch, "nexa_switch", "Nexa Switches"); - protocol_device_add(arctech_switch, "coco_switch", "CoCo Technologies Switches"); - protocol_device_add(arctech_switch, "intertechno_switch", "Intertechno Switches"); - arctech_switch->devtype = SWITCH; - arctech_switch->hwtype = RF433; - arctech_switch->txrpt = NORMAL_REPEATS; - arctech_switch->minrawlen = RAW_LENGTH; - arctech_switch->maxrawlen = RAW_LENGTH; - arctech_switch->maxgaplen = MAX_PULSE_LENGTH*PULSE_DIV; - arctech_switch->mingaplen = MIN_PULSE_LENGTH*PULSE_DIV; - - options_add(&arctech_switch->options, "t", "on", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); - options_add(&arctech_switch->options, "f", "off", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); - options_add(&arctech_switch->options, "u", "unit", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, "^([0-9]{1}|[1][0-5])$"); - options_add(&arctech_switch->options, "i", "id", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, "^([0-9]{1,7}|[1-5][0-9]{7}|6([0-6][0-9]{6}|7(0[0-9]{5}|10([0-7][0-9]{3}|8([0-7][0-9]{2}|8([0-5][0-9]|6[0-3]))))))$"); - options_add(&arctech_switch->options, "a", "all", OPTION_OPT_VALUE, DEVICES_OPTIONAL, JSON_NUMBER, NULL, NULL); - options_add(&arctech_switch->options, "l", "learn", OPTION_NO_VALUE, DEVICES_OPTIONAL, JSON_NUMBER, NULL, NULL); - - options_add(&arctech_switch->options, "0", "readonly", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)0, "^[10]{1}$"); - options_add(&arctech_switch->options, "0", "confirm", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)0, "^[10]{1}$"); - - arctech_switch->parseCode=&parseCode; - arctech_switch->createCode=&createCode; - arctech_switch->printHelp=&printHelp; - arctech_switch->validate=&validate; -} - -#if defined(MODULE) && !defined(_WIN32) -void compatibility(struct module_t *module) { - module->name = "arctech_switch"; - module->version = "3.4"; - module->reqversion = "6.0"; - module->reqcommit = "84"; -} - -void init(void) { - arctechSwitchInit(); -} -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/arctech_switch.h b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/arctech_switch.h deleted file mode 100644 index 2bffaee3..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/arctech_switch.h +++ /dev/null @@ -1,27 +0,0 @@ -/* - Copyright (C) 2013 CurlyMo - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#ifndef _PROTOCOL_ARCTECH_SWITCH_H_ -#define _PROTOCOL_ARCTECH_SWITCH_H_ - -#include "../protocol.h" - -struct protocol_t *arctech_switch; -void arctechSwitchInit(void); - -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/arctech_switch_old.c b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/arctech_switch_old.c deleted file mode 100644 index 814cdc46..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/arctech_switch_old.c +++ /dev/null @@ -1,255 +0,0 @@ -/* - Copyright (C) 2013 CurlyMo - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#include -#include -#include -#include - -#include "../../core/pilight.h" -#include "../../core/common.h" -#include "../../core/dso.h" -#include "../../core/log.h" -#include "../protocol.h" -#include "../../core/binary.h" -#include "../../core/gc.h" -#include "arctech_switch_old.h" - -#define PULSE_MULTIPLIER 3 -#define MIN_PULSE_LENGTH 310 -#define MAX_PULSE_LENGTH 405 -#define AVG_PULSE_LENGTH 335 -#define RAW_LENGTH 50 - -static int validate(void) { - if(arctech_switch_old->rawlen == RAW_LENGTH) { - if(arctech_switch_old->raw[arctech_switch_old->rawlen-1] >= (MIN_PULSE_LENGTH*PULSE_DIV) && - arctech_switch_old->raw[arctech_switch_old->rawlen-1] <= (MAX_PULSE_LENGTH*PULSE_DIV)) { - return 0; - } - } - - return -1; -} - -static void createMessage(int id, int unit, int state) { - arctech_switch_old->message = json_mkobject(); - json_append_member(arctech_switch_old->message, "id", json_mknumber(id, 0)); - json_append_member(arctech_switch_old->message, "unit", json_mknumber(unit, 0)); - if(state == 1) - json_append_member(arctech_switch_old->message, "state", json_mkstring("on")); - else - json_append_member(arctech_switch_old->message, "state", json_mkstring("off")); -} - -static void parseCode(void) { - int binary[RAW_LENGTH/4], x = 0, i = 0; - int len = (int)((double)AVG_PULSE_LENGTH*((double)PULSE_MULTIPLIER/2)); - - if(arctech_switch_old->rawlen>RAW_LENGTH) { - logprintf(LOG_ERR, "arctech_switch_old: parsecode - invalid parameter passed %d", arctech_switch_old->rawlen); - return; - } - - for(x=0;xrawlen-3;x+=4) { - // valid telegrams must consist of 0110 and 1001 blocks - int low_high = 0; - if(arctech_switch_old->raw[x] > len) { - low_high |= 1; - } - if(arctech_switch_old->raw[x+1] > len) { - low_high |= 2; - } - if(arctech_switch_old->raw[x+2] > len) { - low_high |= 4; - } - if(arctech_switch_old->raw[x+3] > len) { - low_high |= 8; - } - switch(low_high) { - case 6: - binary[i++] = 1; - break; - case 10: - binary[i++] = 0; - break; - default: - return; // invalid telegram - } - } - - int unit = binToDec(binary, 0, 3); - int state = binary[11]; - int id = binToDec(binary, 4, 8); - createMessage(id, unit, state); -} - -static void createLow(int s, int e) { - int i; - - for(i=s;i<=e;i+=4) { - arctech_switch_old->raw[i]=(AVG_PULSE_LENGTH); - arctech_switch_old->raw[i+1]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - arctech_switch_old->raw[i+2]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - arctech_switch_old->raw[i+3]=(AVG_PULSE_LENGTH); - } -} - -static void createHigh(int s, int e) { - int i; - - for(i=s;i<=e;i+=4) { - arctech_switch_old->raw[i]=(AVG_PULSE_LENGTH); - arctech_switch_old->raw[i+1]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - arctech_switch_old->raw[i+2]=(AVG_PULSE_LENGTH); - arctech_switch_old->raw[i+3]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - } -} - -static void clearCode(void) { - createHigh(0,35); - createLow(36,47); -} - -static void createUnit(int unit) { - int binary[255]; - int length = 0; - int i=0, x=0; - - length = decToBinRev(unit, binary); - for(i=0;i<=length;i++) { - if(binary[i]==1) { - x=i*4; - createLow(x, x+3); - } - } -} - -static void createId(int id) { - int binary[255]; - int length = 0; - int i=0, x=0; - - length = decToBinRev(id, binary); - for(i=0;i<=length;i++) { - if(binary[i]==1) { - x=i*4; - createLow(16+x, 16+x+3); - } - } -} - -static void createState(int state) { - if(state == 0) { - createHigh(44,47); - } -} - -static void createFooter(void) { - arctech_switch_old->raw[48]=(AVG_PULSE_LENGTH); - arctech_switch_old->raw[49]=(PULSE_DIV*AVG_PULSE_LENGTH); -} - -static int createCode(struct JsonNode *code) { - int id = -1; - int unit = -1; - int state = -1; - double itmp = -1; - - if(json_find_number(code, "id", &itmp) == 0) - id = (int)round(itmp); - if(json_find_number(code, "unit", &itmp) == 0) - unit = (int)round(itmp); - if(json_find_number(code, "off", &itmp) == 0) - state=0; - else if(json_find_number(code, "on", &itmp) == 0) - state=1; - - if(id == -1 || unit == -1 || state == -1) { - logprintf(LOG_ERR, "arctech_switch_old: insufficient number of arguments"); - return EXIT_FAILURE; - } else if(id > 31 || id < 0) { - logprintf(LOG_ERR, "arctech_switch_old: invalid id range"); - return EXIT_FAILURE; - } else if(unit > 15 || unit < 0) { - logprintf(LOG_ERR, "arctech_switch_old: invalid unit range"); - return EXIT_FAILURE; - } else { - createMessage(id, unit, state); - clearCode(); - createUnit(unit); - createId(id); - createState(state); - createFooter(); - arctech_switch_old->rawlen = RAW_LENGTH; - } - return EXIT_SUCCESS; -} - -static void printHelp(void) { - printf("\t -t --on\t\t\tsend an on signal\n"); - printf("\t -f --off\t\t\tsend an off signal\n"); - printf("\t -u --unit=unit\t\t\tcontrol a device with this unit code\n"); - printf("\t -i --id=id\t\t\tcontrol a device with this id\n"); -} - -#if !defined(MODULE) && !defined(_WIN32) -__attribute__((weak)) -#endif -void arctechSwitchOldInit(void) { - - protocol_register(&arctech_switch_old); - protocol_set_id(arctech_switch_old, "arctech_switch_old"); - protocol_device_add(arctech_switch_old, "kaku_switch_old", "Old KlikAanKlikUit Switches"); - protocol_device_add(arctech_switch_old, "cogex", "Cogex Switches"); - protocol_device_add(arctech_switch_old, "intertechno_old", "Old Intertechno Switches"); - protocol_device_add(arctech_switch_old, "byebyestandby", "Bye Bye Standby Switches"); - protocol_device_add(arctech_switch_old, "duwi", "Düwi Terminal Switches"); - arctech_switch_old->devtype = SWITCH; - arctech_switch_old->hwtype = RF433; - arctech_switch_old->minrawlen = RAW_LENGTH; - arctech_switch_old->maxrawlen = RAW_LENGTH; - arctech_switch_old->maxgaplen = MAX_PULSE_LENGTH*PULSE_DIV; - arctech_switch_old->mingaplen = MIN_PULSE_LENGTH*PULSE_DIV; - - options_add(&arctech_switch_old->options, "t", "on", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); - options_add(&arctech_switch_old->options, "f", "off", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); - options_add(&arctech_switch_old->options, "u", "unit", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, "^([0-9]{1}|[1][0-5])$"); - options_add(&arctech_switch_old->options, "i", "id", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, "^(3[012]?|[012][0-9]|[0-9]{1})$"); - - options_add(&arctech_switch_old->options, "0", "readonly", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)0, "^[10]{1}$"); - options_add(&arctech_switch_old->options, "0", "confirm", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)0, "^[10]{1}$"); - - arctech_switch_old->parseCode=&parseCode; - arctech_switch_old->createCode=&createCode; - arctech_switch_old->printHelp=&printHelp; - arctech_switch_old->validate=&validate; -} - -#if defined(MODULE) && !defined(_WIN32) -void compatibility(struct module_t *module) { - module->name = "arctech_switch_old"; - module->version = "2.5"; - module->reqversion = "6.0"; - module->reqcommit = "84"; -} - -void init(void) { - arctechSwitchOldInit(); -} -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/arctech_switch_old.h b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/arctech_switch_old.h deleted file mode 100644 index 6ee2228a..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/arctech_switch_old.h +++ /dev/null @@ -1,27 +0,0 @@ -/* - Copyright (C) 2013 CurlyMo - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#ifndef _PROTOCOL_ARCTECH_SWITCH_OLD_H_ -#define _PROTOCOL_ARCTECH_SWITCH_OLD_H_ - -#include "../protocol.h" - -struct protocol_t *arctech_switch_old; -void arctechSwitchOldInit(void); - -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/auriol.c b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/auriol.c deleted file mode 100644 index c6a388af..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/auriol.c +++ /dev/null @@ -1,204 +0,0 @@ -/* - Copyright (C) 2014 Bram1337 & CurlyMo - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#include -#include -#include -#include - -#include "../../core/pilight.h" -#include "../../core/common.h" -#include "../../core/dso.h" -#include "../../core/log.h" -#include "../protocol.h" -#include "../../core/binary.h" -#include "../../core/gc.h" -#include "auriol.h" - -#define PULSE_MULTIPLIER 13 -#define MIN_PULSE_LENGTH 264 -#define MAX_PULSE_LENGTH 274 -#define AVG_PULSE_LENGTH 269 -#define RAW_LENGTH 66 - -typedef struct settings_t { - double id; - double temp; - struct settings_t *next; -} settings_t; - -static struct settings_t *settings = NULL; - -static int validate(void) { - if(auriol->rawlen == RAW_LENGTH) { - if(auriol->raw[auriol->rawlen-1] >= (MIN_PULSE_LENGTH*PULSE_DIV) && - auriol->raw[auriol->rawlen-1] <= (MAX_PULSE_LENGTH*PULSE_DIV)) { - return 0; - } - } - - return -1; -} - -static void parseCode(void) { - int i = 0, x = 0, binary[RAW_LENGTH/2]; - int channel = 0, id = 0, battery = 0; - double temp_offset = 0.0, temperature = 0.0; - - if(auriol->rawlen>RAW_LENGTH) { - logprintf(LOG_ERR, "auriol: parsecode - invalid parameter passed %d", auriol->rawlen); - return; - } - - for(x=1;xrawlen-2;x+=2) { - if(auriol->raw[x] > AVG_PULSE_LENGTH*PULSE_MULTIPLIER) { - binary[i++] = 1; - } else { - binary[i++] = 0; - } - } - - id = binToDecRev(binary, 0, 7); - battery = binary[8]; - channel = 1 + binToDecRev(binary, 10, 11); // channel as id - temperature = (double)binToSignedRev(binary, 12, 23)/10; - // checksum = (double)binToDecRev(binary, 24, 31); been unable to deciper it - struct settings_t *tmp = settings; - while(tmp) { - if(fabs(tmp->id-id) < EPSILON) { - temp_offset = tmp->temp; - break; - } - tmp = tmp->next; - } - - temperature += temp_offset; - - if(channel != 4) { - auriol->message = json_mkobject(); - json_append_member(auriol->message, "id", json_mknumber(id, 0)); - json_append_member(auriol->message, "temperature", json_mknumber(temperature, 1)); - json_append_member(auriol->message, "battery", json_mknumber(battery, 0)); - json_append_member(auriol->message, "channel", json_mknumber(channel, 0)); - } -} - -static int checkValues(struct JsonNode *jvalues) { - struct JsonNode *jid = NULL; - - if((jid = json_find_member(jvalues, "id"))) { - struct settings_t *snode = NULL; - struct JsonNode *jchild = NULL; - struct JsonNode *jchild1 = NULL; - double id = -1; - int match = 0; - - jchild = json_first_child(jid); - while(jchild) { - jchild1 = json_first_child(jchild); - while(jchild1) { - if(strcmp(jchild1->key, "id") == 0) { - id = jchild1->number_; - } - jchild1 = jchild1->next; - } - jchild = jchild->next; - } - - struct settings_t *tmp = settings; - while(tmp) { - if(fabs(tmp->id-id) < EPSILON) { - match = 1; - break; - } - tmp = tmp->next; - } - - if(match == 0) { - if((snode = MALLOC(sizeof(struct settings_t))) == NULL) { - fprintf(stderr, "out of memory\n"); - exit(EXIT_FAILURE); - } - snode->id = id; - snode->temp = 0; - - json_find_number(jvalues, "temperature-offset", &snode->temp); - - snode->next = settings; - settings = snode; - } - } - return 0; -} - -static void gc(void) { - struct settings_t *tmp = NULL; - while(settings) { - tmp = settings; - settings = settings->next; - FREE(tmp); - } - if(settings != NULL) { - FREE(settings); - } -} - -#if !defined(MODULE) && !defined(_WIN32) -__attribute__((weak)) -#endif -void auriolInit(void) { - - protocol_register(&auriol); - protocol_set_id(auriol, "auriol"); - protocol_device_add(auriol, "auriol", "Auriol Weather Stations"); - auriol->devtype = WEATHER; - auriol->hwtype = RF433; - auriol->minrawlen = RAW_LENGTH; - auriol->maxrawlen = RAW_LENGTH; - auriol->maxgaplen = MAX_PULSE_LENGTH*PULSE_DIV; - auriol->mingaplen = MIN_PULSE_LENGTH*PULSE_DIV; - - options_add(&auriol->options, "i", "id", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, "[0-9]"); - options_add(&auriol->options, "c", "channel", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, "[1-3]"); - options_add(&auriol->options, "t", "temperature", OPTION_HAS_VALUE, DEVICES_VALUE, JSON_NUMBER, NULL, "^[0-9]{1,3}$"); - options_add(&auriol->options, "b", "battery", OPTION_HAS_VALUE, DEVICES_VALUE, JSON_NUMBER, NULL, "^[01]$"); - - // options_add(&auriol->options, 0, "decimals", OPTION_HAS_VALUE, DEVICES_SETTING, JSON_NUMBER, (void *)1, "[0-9]"); - options_add(&auriol->options, "0", "temperature-offset", OPTION_HAS_VALUE, DEVICES_SETTING, JSON_NUMBER, (void *)0, "[0-9]"); - options_add(&auriol->options, "0", "temperature-decimals", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)1, "[0-9]"); - options_add(&auriol->options, "0", "show-temperature", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)1, "^[10]{1}$"); - options_add(&auriol->options, "0", "show-battery", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)1, "^[10]{1}$"); - - auriol->parseCode=&parseCode; - auriol->checkValues=&checkValues; - auriol->validate=&validate; - auriol->gc=&gc; -} - -#if defined(MODULE) && !defined(_WIN32) -void compatibility(struct module_t *module) { - module->name = "auriol"; - module->version = "2.3"; - module->reqversion = "6.0"; - module->reqcommit = "84"; -} - -void init(void) { - auriolInit(); -} -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/auriol.h b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/auriol.h deleted file mode 100644 index 96bf3e30..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/auriol.h +++ /dev/null @@ -1,27 +0,0 @@ -/* - Copyright (C) 2014 Bram1337 & CurlyMo - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#ifndef _PROTOCOL_AURIOL_H_ -#define _PROTOCOL_AURIOL_H_ - -#include "../protocol.h" - -struct protocol_t *auriol; -void auriolInit(void); - -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/beamish_switch.c b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/beamish_switch.c deleted file mode 100644 index c50847b2..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/beamish_switch.c +++ /dev/null @@ -1,259 +0,0 @@ -/* - Copyright (C) 2014 CurlyMo & wo-rasp - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#include -#include -#include -#include - -#include "../../core/pilight.h" -#include "../../core/common.h" -#include "../../core/dso.h" -#include "../../core/log.h" -#include "../protocol.h" -#include "../../core/binary.h" -#include "../../core/gc.h" -#include "beamish_switch.h" - -#define PULSE_MULTIPLIER 4 -#define NORMAL_REPEATS 10 -#define MIN_PULSE_LENGTH 318 -#define MAX_PULSE_LENGTH 328 -#define AVG_PULSE_LENGTH 323 -#define RAW_LENGTH 50 - -static int map[7] = {0, 192, 48, 12, 3, 15, 195}; - -static int validate(void) { - if(beamish_switch->rawlen == RAW_LENGTH) { - if(beamish_switch->raw[beamish_switch->rawlen-1] >= (MIN_PULSE_LENGTH*PULSE_DIV) && - beamish_switch->raw[beamish_switch->rawlen-1] <= (MAX_PULSE_LENGTH*PULSE_DIV)) { - return 0; - } - } - - return -1; -} - -static void createMessage(int id, int unit, int state, int all) { - beamish_switch->message = json_mkobject(); - json_append_member(beamish_switch->message, "id", json_mknumber(id, 0)); - if(all == 1) { - json_append_member(beamish_switch->message, "all", json_mknumber(1, 0)); - } else { - json_append_member(beamish_switch->message, "unit", json_mknumber(unit, 0)); - } - if(state == 0) { - json_append_member(beamish_switch->message, "state", json_mkstring("off")); - } - if(state == 1) { - json_append_member(beamish_switch->message, "state", json_mkstring("on")); - } -} - -static void parseCode(void) { - int i = 0, x = 0, y = 0, binary[RAW_LENGTH/2]; - int id = -1, state = -1, unit = -1, all = 0, code = 0; - - if(beamish_switch->rawlen>RAW_LENGTH) { - logprintf(LOG_ERR, "beamish_switch: parsecode - invalid parameter passed %d", beamish_switch->rawlen); - return; - } - - for(x=0;xrawlen;x+=2) { - if(beamish_switch->raw[x] > (int)((double)AVG_PULSE_LENGTH*((double)PULSE_MULTIPLIER/2))) { - binary[i++] = 1; - } else { - binary[i++] = 0; - } - } - - id = binToDecRev(binary, 0, 15); - code = binToDecRev(binary, 16, 23); - - for(y=0;y<7;y++) { - if(map[y] == code) { - unit = y; - break; - } - } - - if(unit == 5) { - state = 1; - all = 1; - } - if(unit == 6) { - state = 0; - all = 1; - } - - createMessage(id, unit, state, all); -} - -static void createHigh(int s, int e) { - int i; - - for(i=s;i<=e;i+=2) { - beamish_switch->raw[i]=(AVG_PULSE_LENGTH); - beamish_switch->raw[i+1]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - } -} - -static void createLow(int s, int e) { - int i; - - for(i=s;i<=e;i+=2) { - beamish_switch->raw[i]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - beamish_switch->raw[i+1]=(AVG_PULSE_LENGTH); - } -} - -static void clearCode(void) { - createHigh(0,47); -} - -static void createId(int id) { - int binary[255]; - int length = 0; - int i=0, x=0; - - length = decToBinRev(id, binary); - for(i=0;i<=length;i++) { - if(binary[i]==1) { - x=i*2; - createLow(31-(x+1), 31-x); - } - } -} - -static void createUnit(int unit) { - int binary[255]; - int length = 0; - int i=0, x=0; - - length = decToBinRev(unit, binary); - for(i=0;i<=length;i++) { - if(binary[i]==1) { - x=i*2; - createLow(47-(x+1), 47-x); - } - } -} - -static void createFooter(void) { - beamish_switch->raw[48]=(AVG_PULSE_LENGTH); - beamish_switch->raw[49]=(PULSE_DIV*AVG_PULSE_LENGTH); -} - -static int createCode(struct JsonNode *code) { - int id = -1; - int unit = -1; - int state = -1; - int all = 0; - double itmp = -1; - - if(json_find_number(code, "id", &itmp) == 0) - id = (int)round(itmp); - if(json_find_number(code, "unit", &itmp) == 0) - unit = (int)round(itmp); - if(json_find_number(code, "all", &itmp) == 0) - all = 1; - if(json_find_number(code, "off", &itmp) == 0) - state=0; - if(json_find_number(code, "on", &itmp) == 0) - state=1; - - if(id == -1 || (unit == -1 && all == 0) || (state == -1 && all == 1)) { - logprintf(LOG_ERR, "beamish_switch: insufficient number of arguments"); - return EXIT_FAILURE; - } else if(id > 65535 || id < 1) { - logprintf(LOG_ERR, "beamish_switch: invalid id range"); - return EXIT_FAILURE; - } else if((unit > 4 || unit < 1) && all == 0) { - logprintf(LOG_ERR, "beamish_switch: invalid unit range"); - return EXIT_FAILURE; - } else { - if(all == 1 && state == 1) - unit = 5; - if(all == 1 && state == 0) - unit = 6; - - createMessage(id, unit, state, all); - clearCode(); - createId(id); - unit = map[unit]; - createUnit(unit); - createFooter(); - beamish_switch->rawlen = RAW_LENGTH; - } - return EXIT_SUCCESS; -} - -static void printHelp(void) { - printf("\t -t --on\t\t\tsend an on signal\n"); - printf("\t -f --off\t\t\tsend an off signal\n"); - printf("\t -u --unit=unit\t\t\tcontrol a device with this unit code\n"); - printf("\t -i --id=id\t\t\tcontrol a device with this id\n"); - printf("\t -a --all\t\t\tsend command to all devices with this id\n"); -} - -#if !defined(MODULE) && !defined(_WIN32) -__attribute__((weak)) -#endif -void beamishSwitchInit(void) { - - protocol_register(&beamish_switch); - protocol_set_id(beamish_switch, "beamish_switch"); - protocol_device_add(beamish_switch, "beamish_switch", "beamish_switch Switches"); - beamish_switch->devtype = SWITCH; - beamish_switch->hwtype = RF433; - beamish_switch->txrpt = NORMAL_REPEATS; - beamish_switch->minrawlen = RAW_LENGTH; - beamish_switch->maxrawlen = RAW_LENGTH; - beamish_switch->maxgaplen = MAX_PULSE_LENGTH*PULSE_DIV; - beamish_switch->mingaplen = MIN_PULSE_LENGTH*PULSE_DIV; - - options_add(&beamish_switch->options, "t", "on", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); - options_add(&beamish_switch->options, "f", "off", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); - options_add(&beamish_switch->options, "u", "unit", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, "^([1-4])$"); - options_add(&beamish_switch->options, "i", "id", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, "^([0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$"); - options_add(&beamish_switch->options, "a", "all", OPTION_NO_VALUE, 0, JSON_NUMBER, NULL, NULL); - - options_add(&beamish_switch->options, "0", "readonly", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)0, "^[10]{1}$"); - options_add(&beamish_switch->options, "0", "confirm", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)0, "^[10]{1}$"); - - beamish_switch->parseCode=&parseCode; - beamish_switch->createCode=&createCode; - beamish_switch->printHelp=&printHelp; - beamish_switch->validate=&validate; -} - -#if defined(MODULE) && !defined(_WIN32) -void compatibility(struct module_t *module) { - module->name = "beamish_switch"; - module->version = "1.2"; - module->reqversion = "6.0"; - module->reqcommit = "84"; -} - -void init(void) { - beamishSwitchInit(); -} -#endif - - diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/beamish_switch.h b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/beamish_switch.h deleted file mode 100644 index a8b36283..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/beamish_switch.h +++ /dev/null @@ -1,28 +0,0 @@ -/* - Copyright (C) 2014 CurlyMo & wo-rasp - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#ifndef _PROTOCOL_BEAMISH_SWITCH_H_ -#define _PROTOCOL_BEAMISH_SWITCH_H_ - -#include "../protocol.h" - -struct protocol_t *beamish_switch; -void beamishSwitchInit(void); - -#endif - diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/clarus.c b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/clarus.c deleted file mode 100644 index 59701ec7..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/clarus.c +++ /dev/null @@ -1,266 +0,0 @@ -/* - Copyright (C) 2013 CurlyMo - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#include -#include -#include -#include - -#include "../../core/pilight.h" -#include "../../core/common.h" -#include "../../core/dso.h" -#include "../../core/log.h" -#include "../protocol.h" -#include "../../core/binary.h" -#include "../../core/gc.h" -#include "clarus.h" - -#define PULSE_MULTIPLIER 3 -#define MIN_PULSE_LENGTH 160 -#define MAX_PULSE_LENGTH 200 -#define AVG_PULSE_LENGTH 180 -#define RAW_LENGTH 50 - -static int validate(void) { - if(clarus_switch->rawlen == RAW_LENGTH) { - if(clarus_switch->raw[clarus_switch->rawlen-1] >= (MIN_PULSE_LENGTH*PULSE_DIV) && - clarus_switch->raw[clarus_switch->rawlen-1] <= (MAX_PULSE_LENGTH*PULSE_DIV)) { - return 0; - } - } - - return -1; -} - -static void createMessage(const char *id, int unit, int state) { - clarus_switch->message = json_mkobject(); - json_append_member(clarus_switch->message, "id", json_mkstring(id)); - json_append_member(clarus_switch->message, "unit", json_mknumber(unit, 0)); - if(state == 2) - json_append_member(clarus_switch->message, "state", json_mkstring("on")); - else - json_append_member(clarus_switch->message, "state", json_mkstring("off")); -} - -static void parseCode(void) { - int x = 0, z = 65, binary[RAW_LENGTH/4]; - char id[3]; - - if(clarus_switch->rawlen>RAW_LENGTH) { - logprintf(LOG_ERR, "clarus_switch: parsecode - invalid parameter passed %d", clarus_switch->rawlen); - return; - } - - /* Convert the one's and zero's into binary */ - for(x=0;xrawlen-2;x+=4) { - if(clarus_switch->raw[x+3] > (int)((double)AVG_PULSE_LENGTH*((double)PULSE_MULTIPLIER/2))) { - binary[x/4]=1; - } else if(clarus_switch->raw[x+0] > (int)((double)AVG_PULSE_LENGTH*((double)PULSE_MULTIPLIER/2))) { - binary[x/4]=2; - } else { - binary[x/4]=0; - } - } - - for(x=9;x>=5;--x) { - if(binary[x] == 2) { - break; - } - z++; - } - - int unit = binToDecRev(binary, 0, 5); - int state = binary[11]; - int y = binToDecRev(binary, 6, 9); - sprintf(&id[0], "%c%d", z, y); - - createMessage(id, unit, state); -} - -static void createLow(int s, int e) { - int i; - - for(i=s;i<=e;i+=4) { - clarus_switch->raw[i]=(AVG_PULSE_LENGTH); - clarus_switch->raw[i+1]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - clarus_switch->raw[i+2]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - clarus_switch->raw[i+3]=(AVG_PULSE_LENGTH); - } -} - -static void createMed(int s, int e) { - int i; - - for(i=s;i<=e;i+=4) { - clarus_switch->raw[i]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - clarus_switch->raw[i+1]=(AVG_PULSE_LENGTH); - clarus_switch->raw[i+2]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - clarus_switch->raw[i+3]=(AVG_PULSE_LENGTH); - } -} - -static void createHigh(int s, int e) { - int i; - - for(i=s;i<=e;i+=4) { - clarus_switch->raw[i]=(AVG_PULSE_LENGTH); - clarus_switch->raw[i+1]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - clarus_switch->raw[i+2]=(AVG_PULSE_LENGTH); - clarus_switch->raw[i+3]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - } -} - -static void clearCode(void) { - createLow(0,47); -} - -static void createUnit(int unit) { - int binary[255]; - int length = 0; - int i=0, x=0; - - length = decToBinRev(unit, binary); - for(i=0;i<=length;i++) { - if(binary[i]==1) { - x=i*4; - createHigh(23-(x+3), 23-x); - } - } -} - -static void createId(const char *id) { - int l = ((int)(id[0]))-65; - int y = atoi(&id[1]); - int binary[255]; - int length = 0; - int i=0, x=0; - - length = decToBinRev(y, binary); - for(i=0;i<=length;i++) { - x=i*4; - if(binary[i]==1) { - createHigh(39-(x+3), 39-x); - } - } - x=(l*4); - createMed(39-(x+3), 39-x); -} - -static void createState(int state) { - if(state == 0) { - createMed(40,43); - createHigh(44,47); - } else { - createHigh(40,43); - createMed(44,47); - } -} - -static void createFooter(void) { - clarus_switch->raw[48]=(AVG_PULSE_LENGTH); - clarus_switch->raw[49]=(PULSE_DIV*AVG_PULSE_LENGTH); -} - -static int createCode(struct JsonNode *code) { - const char *id = NULL; - int unit = -1; - int state = -1; - double itmp; - char *stmp; - - if(json_find_string(code, "id", &stmp) == 0) - id = stmp; - if(json_find_number(code, "off", &itmp) == 0) - state=0; - else if(json_find_number(code, "on", &itmp) == 0) - state=1; - if(json_find_number(code, "unit", &itmp) == 0) - unit = (int)round(itmp); - - if(id == NULL || unit == -1 || state == -1) { - logprintf(LOG_ERR, "clarus_switch: insufficient number of arguments"); - return EXIT_FAILURE; - } else if((int)(id[0]) < 65 || (int)(id[0]) > 70) { - logprintf(LOG_ERR, "clarus_switch: invalid id range"); - return EXIT_FAILURE; - } else if(atoi(&id[1]) < 0 || atoi(&id[1]) > 31) { - logprintf(LOG_ERR, "clarus_switch: invalid id range"); - return EXIT_FAILURE; - } else if(unit > 63 || unit < 0) { - logprintf(LOG_ERR, "clarus_switch: invalid unit range"); - return EXIT_FAILURE; - } else { - createMessage(id, unit, ((state == 2 || state == 1) ? 2 : 0)); - clearCode(); - createUnit(unit); - createId(id); - createState(state); - createFooter(); - clarus_switch->rawlen = RAW_LENGTH; - } - return EXIT_SUCCESS; -} - -static void printHelp(void) { - printf("\t -t --on\t\t\tsend an on signal\n"); - printf("\t -f --off\t\t\tsend an off signal\n"); - printf("\t -u --unit=unit\t\t\tcontrol a device with this unit code\n"); - printf("\t -i --id=id\t\t\tcontrol a device with this id\n"); -} - -#if !defined(MODULE) && !defined(_WIN32) -__attribute__((weak)) -#endif -void clarusSwitchInit(void) { - - protocol_register(&clarus_switch); - protocol_set_id(clarus_switch, "clarus_switch"); - protocol_device_add(clarus_switch, "clarus_switch", "Clarus Switches"); - clarus_switch->devtype = SWITCH; - clarus_switch->hwtype = RF433; - clarus_switch->minrawlen = RAW_LENGTH; - clarus_switch->maxrawlen = RAW_LENGTH; - clarus_switch->maxgaplen = MAX_PULSE_LENGTH*PULSE_DIV; - clarus_switch->mingaplen = MIN_PULSE_LENGTH*PULSE_DIV; - - options_add(&clarus_switch->options, "t", "on", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); - options_add(&clarus_switch->options, "f", "off", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); - options_add(&clarus_switch->options, "u", "unit", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, "^([0-9]|[1-5][0-9]|6[0-3])$"); - options_add(&clarus_switch->options, "i", "id", OPTION_HAS_VALUE, DEVICES_ID, JSON_STRING, NULL, "^[ABCDEF](3[012]?|[012][0-9]|[0-9]{1})$"); - - options_add(&clarus_switch->options, "0", "readonly", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)0, "^[10]{1}$"); - options_add(&clarus_switch->options, "0", "confirm", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)0, "^[10]{1}$"); - - clarus_switch->parseCode=&parseCode; - clarus_switch->createCode=&createCode; - clarus_switch->printHelp=&printHelp; - clarus_switch->validate=&validate; -} - -#if defined(MODULE) && !defined(_WIN32) -void compatibility(struct module_t *module) { - module->name = "clarus_switch"; - module->version = "2.4"; - module->reqversion = "6.0"; - module->reqcommit = "84"; -} - -void init(void) { - clarusSwitchInit(); -} -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/clarus.h b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/clarus.h deleted file mode 100644 index 93ed23f4..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/clarus.h +++ /dev/null @@ -1,27 +0,0 @@ -/* - Copyright (C) 2013 CurlyMo - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#ifndef _PROTOCOL_CLARUS_H_ -#define _PROTOCOL_CLARUS_H_ - -#include "../protocol.h" - -struct protocol_t *clarus_switch; -void clarusSwitchInit(void); - -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/cleverwatts.c b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/cleverwatts.c deleted file mode 100644 index b3bd13d7..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/cleverwatts.c +++ /dev/null @@ -1,248 +0,0 @@ -/* - Copyright (C) 2014 CurlyMo - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#include -#include -#include -#include - -#include "../../core/pilight.h" -#include "../../core/common.h" -#include "../../core/dso.h" -#include "../../core/log.h" -#include "../protocol.h" -#include "../../core/binary.h" -#include "../../core/gc.h" -#include "cleverwatts.h" - -#define PULSE_MULTIPLIER 4 -#define MIN_PULSE_LENGTH 265 -#define MAX_PULSE_LENGTH 274 -#define AVG_PULSE_LENGTH 269 -#define RAW_LENGTH 50 - -static int validate(void) { - if(cleverwatts->rawlen == RAW_LENGTH) { - if(cleverwatts->raw[cleverwatts->rawlen-1] >= (MIN_PULSE_LENGTH*PULSE_DIV) && - cleverwatts->raw[cleverwatts->rawlen-1] <= (MAX_PULSE_LENGTH*PULSE_DIV)) { - return 0; - } - } - - return -1; -} - -static void createMessage(int id, int unit, int state, int all) { - cleverwatts->message = json_mkobject(); - json_append_member(cleverwatts->message, "id", json_mknumber(id, 0)); - if(all == 0) { - json_append_member(cleverwatts->message, "all", json_mknumber(1, 0)); - } else { - json_append_member(cleverwatts->message, "unit", json_mknumber(unit, 0)); - } - if(state == 0) - json_append_member(cleverwatts->message, "state", json_mkstring("on")); - else - json_append_member(cleverwatts->message, "state", json_mkstring("off")); -} - -static void parseCode(void) { - int i = 0, x = 0, binary[RAW_LENGTH/2]; - int id = 0, state = 0, unit = 0, all = 0; - - if(cleverwatts->rawlen>RAW_LENGTH) { - logprintf(LOG_ERR, "cleverwatts: parsecode - invalid parameter passed %d", cleverwatts->rawlen); - return; - } - - for(x=1;xrawlen-1;x+=2) { - if(cleverwatts->raw[x] > (int)((double)AVG_PULSE_LENGTH*((double)PULSE_MULTIPLIER/2))) { - binary[i++] = 1; - } else { - binary[i++] = 0; - } - } - - id = binToDecRev(binary, 0, 19); - state = binary[20]; - unit = binToDecRev(binary, 21, 22); - all = binary[23]; - - createMessage(id, unit, state, all); -} - -static void createLow(int s, int e) { - int i; - - for(i=s;i<=e;i+=2) { - cleverwatts->raw[i]=(AVG_PULSE_LENGTH); - cleverwatts->raw[i+1]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - } -} - -static void createHigh(int s, int e) { - int i; - - for(i=s;i<=e;i+=2) { - cleverwatts->raw[i]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - cleverwatts->raw[i+1]=(AVG_PULSE_LENGTH); - } -} - -static void clearCode(void) { - createHigh(0,47); -} - -static void createId(int id) { - int binary[255]; - int length = 0; - int i=0, x=0; - - length = decToBinRev(id, binary); - for(i=0;i<=length;i++) { - if(binary[i]==1) { - x=i*2; - createLow(39-(x+1), 39-x); - } - } -} - -static void createAll(int all) { - if(all == 0) { - createLow(46, 47); - } -} - -static void createState(int state) { - if(state == 1) { - createLow(40, 41); - } -} - -static void createUnit(int unit) { - int binary[255]; - int length = 0; - int i=0, x=0; - - length = decToBinRev(unit, binary); - for(i=0;i<=length;i++) { - if(binary[i]==1) { - x=i*2; - createLow(45-(x+1), 45-x); - } - } -} - -static void createFooter(void) { - cleverwatts->raw[48]=(AVG_PULSE_LENGTH); - cleverwatts->raw[49]=(PULSE_DIV*AVG_PULSE_LENGTH); -} - -static int createCode(struct JsonNode *code) { - int id = -1; - int unit = -1; - int state = -1; - int all = 0; - double itmp = -1; - - if(json_find_number(code, "id", &itmp) == 0) - id = (int)round(itmp); - if(json_find_number(code, "unit", &itmp) == 0) - unit = (int)round(itmp); - if(json_find_number(code, "all", &itmp) == 0) - all = (int)round(itmp); - if(json_find_number(code, "off", &itmp) == 0) - state=1; - else if(json_find_number(code, "on", &itmp) == 0) - state=0; - - if(id == -1 || (unit == -1 && all == 0) || state == -1) { - logprintf(LOG_ERR, "cleverwatts: insufficient number of arguments"); - return EXIT_FAILURE; - } else if(id > 1048575 || id < 1) { - logprintf(LOG_ERR, "cleverwatts: invalid id range"); - return EXIT_FAILURE; - } else if((unit > 3 || unit < 0) && all == 0) { - logprintf(LOG_ERR, "cleverwatts: invalid unit range"); - return EXIT_FAILURE; - } else { - if(unit == -1 && all == 1) { - unit = 3; - } - createMessage(id, unit, state, all ^ 1); - clearCode(); - createId(id); - createState(state); - createUnit(unit); - createAll(all); - createFooter(); - cleverwatts->rawlen = RAW_LENGTH; - } - return EXIT_SUCCESS; -} - -static void printHelp(void) { - printf("\t -t --on\t\t\tsend an on signal\n"); - printf("\t -f --off\t\t\tsend an off signal\n"); - printf("\t -u --unit=unit\t\t\tcontrol a device with this unit code\n"); - printf("\t -i --id=id\t\t\tcontrol a device with this id\n"); - printf("\t -a --all\t\t\tsend command to all devices with this id\n"); -} - -#if !defined(MODULE) && !defined(_WIN32) -__attribute__((weak)) -#endif -void cleverwattsInit(void) { - - protocol_register(&cleverwatts); - protocol_set_id(cleverwatts, "cleverwatts"); - protocol_device_add(cleverwatts, "cleverwatts", "Cleverwatts Switches"); - cleverwatts->devtype = SWITCH; - cleverwatts->hwtype = RF433; - cleverwatts->minrawlen = RAW_LENGTH; - cleverwatts->maxrawlen = RAW_LENGTH; - cleverwatts->maxgaplen = MAX_PULSE_LENGTH*PULSE_DIV; - cleverwatts->mingaplen = MIN_PULSE_LENGTH*PULSE_DIV; - - options_add(&cleverwatts->options, "t", "on", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); - options_add(&cleverwatts->options, "f", "off", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); - options_add(&cleverwatts->options, "u", "unit", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, "^([0-3])$"); - options_add(&cleverwatts->options, "i", "id", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, "^([0-9]{1,6}|10([0-3][0-9]{4}|4([0-7][0-9]{3}|8([0-4][0-9]{2}|5([0-6][0-9]|7[0-5])))))$"); - options_add(&cleverwatts->options, "a", "all", OPTION_OPT_VALUE, DEVICES_OPTIONAL, JSON_NUMBER, NULL, NULL); - - options_add(&cleverwatts->options, "0", "readonly", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)0, "^[10]{1}$"); - options_add(&cleverwatts->options, "0", "confirm", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)0, "^[10]{1}$"); - - cleverwatts->parseCode=&parseCode; - cleverwatts->createCode=&createCode; - cleverwatts->printHelp=&printHelp; - cleverwatts->validate=&validate; -} - -#if defined(MODULE) && !defined(_WIN32) -void compatibility(struct module_t *module) { - module->name = "cleverwatts"; - module->version = "1.1"; - module->reqversion = "6.0"; - module->reqcommit = "84"; -} - -void init(void) { - cleverwattsInit(); -} -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/cleverwatts.h b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/cleverwatts.h deleted file mode 100644 index f2ddcc84..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/cleverwatts.h +++ /dev/null @@ -1,27 +0,0 @@ -/* - Copyright (C) 2014 CurlyMo - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#ifndef _PROTOCOL_CLEVERWATTS_H_ -#define _PROTOCOL_CLEVERWATTS_H_ - -#include "../protocol.h" - -struct protocol_t *cleverwatts; -void cleverwattsInit(void); - -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/conrad_rsl_contact.c b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/conrad_rsl_contact.c deleted file mode 100644 index 1da8d7e6..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/conrad_rsl_contact.c +++ /dev/null @@ -1,120 +0,0 @@ -/* - Copyright (C) 2013 CurlyMo & Bram1337 - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#include -#include -#include - -#include "../../core/pilight.h" -#include "../../core/common.h" -#include "../../core/dso.h" -#include "../../core/log.h" -#include "../protocol.h" -#include "../../core/binary.h" -#include "../../core/gc.h" -#include "conrad_rsl_contact.h" - -#define PULSE_MULTIPLIER 5 -#define MIN_PULSE_LENGTH 185 -#define MAX_PULSE_LENGTH 195 -#define AVG_PULSE_LENGTH 190 -#define RAW_LENGTH 66 - -static int validate(void) { - if(conrad_rsl_contact->rawlen == RAW_LENGTH) { - if(conrad_rsl_contact->raw[conrad_rsl_contact->rawlen-1] >= (MIN_PULSE_LENGTH*PULSE_DIV) && - conrad_rsl_contact->raw[conrad_rsl_contact->rawlen-1] <= (MAX_PULSE_LENGTH*PULSE_DIV)) { - return 0; - } - } - - return -1; -} - -static void createMessage(int id, int state) { - conrad_rsl_contact->message = json_mkobject(); - json_append_member(conrad_rsl_contact->message, "id", json_mknumber(id, 0)); - if(state == 1) { - json_append_member(conrad_rsl_contact->message, "state", json_mkstring("opened")); - } else { - json_append_member(conrad_rsl_contact->message, "state", json_mkstring("closed")); - } -} - -static void parseCode(void) { - int x = 0, binary[RAW_LENGTH/2]; - - if(conrad_rsl_contact->rawlen>RAW_LENGTH) { - logprintf(LOG_ERR, "conrad_rsl_contact: parsecode - invalid parameter passed %d", conrad_rsl_contact->rawlen); - return; - } - - /* Convert the one's and zero's into binary */ - for(x=0; xrawlen; x+=2) { - if(conrad_rsl_contact->raw[x+1] > (int)((double)AVG_PULSE_LENGTH*((double)PULSE_MULTIPLIER/2))) { - binary[x/2]=1; - } else { - binary[x/2]=0; - } - } - - int id = binToDecRev(binary, 6, 31); - int check = binToDecRev(binary, 0, 3); - int check1 = binary[32]; - int state = binary[4]; - - if(check == 5 && check1 == 1) { - createMessage(id, state); - } -} - -#if !defined(MODULE) && !defined(_WIN32) -__attribute__((weak)) -#endif -void conradRSLContactInit(void) { - - protocol_register(&conrad_rsl_contact); - protocol_set_id(conrad_rsl_contact, "conrad_rsl_contact"); - protocol_device_add(conrad_rsl_contact, "conrad_rsl_contact", "Conrad RSL Contact Sensor"); - conrad_rsl_contact->devtype = CONTACT; - conrad_rsl_contact->hwtype = RF433; - conrad_rsl_contact->minrawlen = RAW_LENGTH; - conrad_rsl_contact->maxrawlen = RAW_LENGTH; - conrad_rsl_contact->maxgaplen = MAX_PULSE_LENGTH*PULSE_DIV; - conrad_rsl_contact->mingaplen = MIN_PULSE_LENGTH*PULSE_DIV; - - options_add(&conrad_rsl_contact->options, "i", "id", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, "^(([0-9]|([1-9][0-9])|([1-9][0-9]{2})|([1-9][0-9]{3})|([1-9][0-9]{4})|([1-9][0-9]{5})|([1-9][0-9]{6})|((6710886[0-3])|(671088[0-5][0-9])|(67108[0-7][0-9]{2})|(6710[0-7][0-9]{3})|(671[0--1][0-9]{4})|(670[0-9]{5})|(6[0-6][0-9]{6})|(0[0-5][0-9]{7}))))$"); - options_add(&conrad_rsl_contact->options, "t", "opened", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); - options_add(&conrad_rsl_contact->options, "f", "closed", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); - - conrad_rsl_contact->parseCode=&parseCode; - conrad_rsl_contact->validate=&validate; -} - -#if defined(MODULE) && !defined(_WIN32) -void compatibility(struct module_t *module) { - module->name = "conrad_rsl_contact"; - module->version = "2.3"; - module->reqversion = "6.0"; - module->reqcommit = "84"; -} - -void init(void) { - conradRSLContactInit(); -} -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/conrad_rsl_contact.h b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/conrad_rsl_contact.h deleted file mode 100644 index 5835bb0e..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/conrad_rsl_contact.h +++ /dev/null @@ -1,27 +0,0 @@ -/* - Copyright (C) 2013 CurlyMo & Bram1337 - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#ifndef _PROTOCOL_CONRAD_RSL_CN_H_ -#define _PROTOCOL_CONRAD_RSL_CN_H_ - -#include "../protocol.h" - -struct protocol_t *conrad_rsl_contact; -void conradRSLContactInit(void); - -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/conrad_rsl_switch.c b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/conrad_rsl_switch.c deleted file mode 100644 index 1a598135..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/conrad_rsl_switch.c +++ /dev/null @@ -1,316 +0,0 @@ -/* - Copyright (C) 2013 CurlyMo & Bram1337 - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#include -#include -#include -#include - -#include "../../core/pilight.h" -#include "../../core/common.h" -#include "../../core/dso.h" -#include "../../core/log.h" -#include "../protocol.h" -#include "../../core/binary.h" -#include "../../core/gc.h" -#include "conrad_rsl_switch.h" - -#define LEARN_REPEATS 40 -#define NORMAL_REPEATS 10 -#define PULSE_MULTIPLIER 6 -#define MIN_PULSE_LENGTH 190 -#define MAX_PULSE_LENGTH 210 -#define AVG_PULSE_LENGTH 200 -#define RAW_LENGTH 66 - -static int codes[5][4][2]; - -static int validate(void) { - if(conrad_rsl_switch->rawlen == RAW_LENGTH) { - if(conrad_rsl_switch->raw[conrad_rsl_switch->rawlen-1] >= (MIN_PULSE_LENGTH*PULSE_DIV) && - conrad_rsl_switch->raw[conrad_rsl_switch->rawlen-1] <= (MAX_PULSE_LENGTH*PULSE_DIV)) { - return 0; - } - } - - return -1; -} - -static void createMessage(int id, int unit, int state, int learn) { - conrad_rsl_switch->message = json_mkobject(); - - if(id == 4) { - json_append_member(conrad_rsl_switch->message, "all", json_mknumber(1, 0)); - } else { - json_append_member(conrad_rsl_switch->message, "id", json_mknumber(id+1, 0)); - } - json_append_member(conrad_rsl_switch->message, "unit", json_mknumber(unit+1, 0)); - if(state == 1) { - json_append_member(conrad_rsl_switch->message, "state", json_mkstring("on")); - } else { - json_append_member(conrad_rsl_switch->message, "state", json_mkstring("off")); - } - if(learn == 1) { - conrad_rsl_switch->txrpt = LEARN_REPEATS; - } else { - conrad_rsl_switch->txrpt = NORMAL_REPEATS; - } -} - -static void parseCode(void) { - int x = 0, binary[RAW_LENGTH/2]; - int id = 0, unit = 0, state = 0; - - if(conrad_rsl_switch->rawlen>RAW_LENGTH) { - logprintf(LOG_ERR, "conrad_rsl_switch: parsecode - invalid parameter passed %d", conrad_rsl_switch->rawlen); - return; - } - - /* Convert the one's and zero's into binary */ - for(x=0;xrawlen;x+=2) { - if(conrad_rsl_switch->raw[x+1] > (int)((double)AVG_PULSE_LENGTH*((double)PULSE_MULTIPLIER/2))) { - binary[x/2]=0; - } else { - binary[x/2]=1; - } - } - - int check = binToDecRev(binary, 0, 7); - int match = 0; - for(id=0;id<5;id++) { - for(unit=0;unit<4;unit++) { - if(codes[id][unit][0] == check) { - state = 0; - match = 1; - } - if(codes[id][unit][1] == check) { - state = 1; - match = 1; - } - if(match) { - break; - } - } - if(match) { - break; - } - } - createMessage(id, unit, state, 0); -} - -static void createLow(int s, int e) { - int i; - - for(i=s;i<=e;i+=2) { - conrad_rsl_switch->raw[i]=((PULSE_MULTIPLIER+1)*AVG_PULSE_LENGTH); - conrad_rsl_switch->raw[i+1]=AVG_PULSE_LENGTH*3; - } -} - -static void createHigh(int s, int e) { - int i; - - for(i=s;i<=e;i+=2) { - conrad_rsl_switch->raw[i]=AVG_PULSE_LENGTH*3; - conrad_rsl_switch->raw[i+1]=((PULSE_MULTIPLIER+1)*AVG_PULSE_LENGTH); - } -} - -static void clearCode(void) { - int i = 0, x = 0; - createHigh(0,65); - // for(i=0;i<65;i+=2) { - // x=i*2; - // createHigh(x,x+1); - // } - - int binary[255]; - int length = 0; - - length = decToBinRev(23876, binary); - for(i=0;i<=length;i++) { - x=i*2; - if(binary[i]==1) { - createLow(x+16, x+16+1); - } else { - createHigh(x+16, x+16+1); - } - } -} - -static void createId(int id, int unit, int state) { - int binary[255]; - int length = 0; - int i=0, x=0; - - int code = codes[id][unit][state]; - - length = decToBin(code, binary); - for(i=0;i<=length;i++) { - x=i*2; - if(binary[i]==1) { - createLow(x, x+1); - } else { - createHigh(x, x+1); - } - } -} - -static void createFooter(void) { - conrad_rsl_switch->raw[64]=(AVG_PULSE_LENGTH*3); - conrad_rsl_switch->raw[65]=(PULSE_DIV*AVG_PULSE_LENGTH); -} - -static int createCode(struct JsonNode *code) { - int id = -1; - int state = -1; - int unit = -1; - int all = 0; - int learn = -1; - double itmp = 0; - - if(json_find_number(code, "id", &itmp) == 0) - id = (int)round(itmp); - if(json_find_number(code, "unit", &itmp) == 0) - unit = (int)round(itmp); - if(json_find_number(code, "all", &itmp) == 0) - all = 1; - if(json_find_number(code, "off", &itmp) == 0) - state=0; - else if(json_find_number(code, "on", &itmp) == 0) - state=1; - if(json_find_number(code, "learn", &itmp) == 0) - learn = 1; - - if(unit == -1 || (id == -1 && all == 0) || state == -1) { - logprintf(LOG_ERR, "conrad_rsl_switch: insufficient number of arguments"); - return EXIT_FAILURE; - } else if((id > 5 || id < 0) && all == 0) { - logprintf(LOG_ERR, "conrad_rsl_switch: invalid id range"); - return EXIT_FAILURE; - } else if(unit > 5 || unit < 0) { - logprintf(LOG_ERR, "conrad_rsl_switch: invalid unit range"); - return EXIT_FAILURE; - } else { - if(all == 1) { - id = 5; - } - id -= 1; - unit -= 1; - createMessage(id, unit, state, learn); - clearCode(); - createId(id, unit, state); - createFooter(); - conrad_rsl_switch->rawlen = RAW_LENGTH; - } - return EXIT_SUCCESS; -} - -static void printHelp(void) { - printf("\t -i --id=id\tcontrol a device with this id\n"); - printf("\t -i --unit=unit\tcontrol a device with this unit\n"); - printf("\t -t --on\t\t\tsend an on signal\n"); - printf("\t -f --off\t\t\tsend an off signal\n"); - printf("\t -a --all\t\t\tsend an all signal\n"); - printf("\t -l --learn\t\t\tsend multiple streams so switch can learn\n"); -} - -#if !defined(MODULE) && !defined(_WIN32) -__attribute__((weak)) -#endif -void conradRSLSwitchInit(void) { - - memset(codes, 0, 33); - codes[0][0][0] = 190; - codes[0][0][1] = 182; - codes[0][1][0] = 129; - codes[0][1][1] = 142; - codes[0][2][0] = 174; - codes[0][2][1] = 166; - codes[0][3][0] = 158; - codes[0][3][1] = 150; - - codes[1][0][0] = 181; - codes[1][0][1] = 185; - codes[1][1][0] = 141; - codes[1][1][1] = 133; - codes[1][2][0] = 165; - codes[1][2][1] = 169; - codes[1][3][0] = 149; - codes[1][3][1] = 153; - - codes[2][0][0] = 184; - codes[2][0][1] = 176; - codes[2][1][0] = 132; - codes[2][1][1] = 136; - codes[2][2][0] = 168; - codes[2][2][1] = 160; - codes[2][3][0] = 152; - codes[2][3][1] = 144; - - codes[3][0][0] = 178; - codes[3][0][1] = 188; - codes[3][1][0] = 138; - codes[3][1][1] = 130; - codes[3][2][0] = 162; - codes[3][2][1] = 172; - codes[3][3][0] = 146; - codes[3][3][1] = 156; - - codes[4][0][0] = 163; - codes[4][0][1] = 147; - - protocol_register(&conrad_rsl_switch); - protocol_set_id(conrad_rsl_switch, "conrad_rsl_switch"); - protocol_device_add(conrad_rsl_switch, "conrad_rsl_switch", "Conrad RSL Switches"); - conrad_rsl_switch->devtype = SWITCH; - conrad_rsl_switch->hwtype = RF433; - conrad_rsl_switch->txrpt = NORMAL_REPEATS; - conrad_rsl_switch->minrawlen = RAW_LENGTH; - conrad_rsl_switch->maxrawlen = RAW_LENGTH; - conrad_rsl_switch->maxgaplen = MAX_PULSE_LENGTH*PULSE_DIV; - conrad_rsl_switch->mingaplen = MIN_PULSE_LENGTH*PULSE_DIV; - - options_add(&conrad_rsl_switch->options, "i", "id", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, "^[1-4]$"); - options_add(&conrad_rsl_switch->options, "u", "unit", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, "^[1-4]$"); - options_add(&conrad_rsl_switch->options, "t", "on", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); - options_add(&conrad_rsl_switch->options, "f", "off", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); - options_add(&conrad_rsl_switch->options, "a", "all", OPTION_OPT_VALUE, DEVICES_OPTIONAL, JSON_NUMBER, NULL, NULL); - options_add(&conrad_rsl_switch->options, "l", "learn", OPTION_NO_VALUE, DEVICES_OPTIONAL, JSON_NUMBER, NULL, NULL); - - options_add(&conrad_rsl_switch->options, "0", "readonly", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)0, "^[10]{1}$"); - options_add(&conrad_rsl_switch->options, "0", "confirm", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)0, "^[10]{1}$"); - - conrad_rsl_switch->parseCode=&parseCode; - conrad_rsl_switch->createCode=&createCode; - conrad_rsl_switch->printHelp=&printHelp; - conrad_rsl_switch->validate=&validate; -} - -#if defined(MODULE) && !defined(_WIN32) -void compatibility(struct module_t *module) { - module->name = "conrad_rsl_switch"; - module->version = "2.3"; - module->reqversion = "6.0"; - module->reqcommit = "84"; -} - -void init(void) { - conradRSLSwitchInit(); -} -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/conrad_rsl_switch.h b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/conrad_rsl_switch.h deleted file mode 100644 index 21e2748e..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/conrad_rsl_switch.h +++ /dev/null @@ -1,27 +0,0 @@ -/* - Copyright (C) 2013 CurlyMo & Bram1337 - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#ifndef _PROTOCOL_CONRAD_RSL_SW_H_ -#define _PROTOCOL_CONRAD_RSL_SW_H_ - -#include "../protocol.h" - -struct protocol_t *conrad_rsl_switch; -void conradRSLSwitchInit(void); - -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/daycom.c b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/daycom.c deleted file mode 100644 index 90abd6e4..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/daycom.c +++ /dev/null @@ -1,251 +0,0 @@ -/* - Copyright (C) 2015 CurlyMo & Rafael - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#include -#include -#include -#include - -#include "../../core/pilight.h" -#include "../../core/common.h" -#include "../../core/dso.h" -#include "../../core/log.h" -#include "../../core/binary.h" -#include "../../core/gc.h" -#include "../protocol.h" -#include "daycom.h" - -#define PULSE_MULTIPLIER 4 -#define MIN_PULSE_LENGTH 280 -#define MAX_PULSE_LENGTH 296 -#define AVG_PULSE_LENGTH 284 -#define RAW_LENGTH 50 - -static int validate(void) { - if(daycom->rawlen == RAW_LENGTH) { - if(daycom->raw[daycom->rawlen-1] >= (MIN_PULSE_LENGTH*PULSE_DIV) && - daycom->raw[daycom->rawlen-1] <= (MAX_PULSE_LENGTH*PULSE_DIV)) { - return 0; - } - } - - return -1; -} - -static void createMessage(int id, int systemcode, int unit, int state) { - daycom->message = json_mkobject(); - json_append_member(daycom->message, "id", json_mknumber(id, 0)); - json_append_member(daycom->message, "systemcode", json_mknumber(systemcode, 0)); - json_append_member(daycom->message, "unit", json_mknumber(unit, 0)); - if(state == 0) { - json_append_member(daycom->message, "state", json_mkstring("on")); - } else { - json_append_member(daycom->message, "state", json_mkstring("off")); - } -} - -static void parseCode(void) { - int binary[RAW_LENGTH/2], x = 0, i = 0; - int id = -1, state = -1, unit = -1, systemcode = -1; - - if(daycom->rawlen>RAW_LENGTH) { - logprintf(LOG_ERR, "daycom: parsecode - invalid parameter passed %d", daycom->rawlen); - return; - } - - for(x=0;xrawlen;x+=2) { - if(daycom->raw[x] > AVG_PULSE_LENGTH*(PULSE_MULTIPLIER/2)) { - binary[i++] = 1; - } else { - binary[i++] = 0; - } - } - - id = binToDecRev(binary, 0, 5); - systemcode = binToDecRev(binary, 6, 19); - unit = binToDecRev(binary, 21, 23 ); - state = binary[20]; - createMessage(id, systemcode, unit, state); -} - -static void createLow(int s, int e) { - int i; - for(i=s;i<=e;i+=2) { - daycom->raw[i]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - daycom->raw[i+1]=(AVG_PULSE_LENGTH); - } -} -static void createHigh(int s, int e) { - int i; - for(i=s;i<=e;i+=2) { - daycom->raw[i]=(AVG_PULSE_LENGTH); - daycom->raw[i+1]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - } -} - -static void clearCode(void) { - createHigh(0,47); -} - -static void createId(int id) { - int binary[255]; - int length = 0; - int i=0, x=0; - - length = decToBinRev(id, binary); - for(i=0;i<=length;i++) { - if(binary[i]==1) { - x=i*2; - createLow(11-(x+1), 11-x); - } - } -} - - -static void createSystemCode(int systemcode) { - int binary[255]; - int length = 0; - int i=0, x=0; - - length = decToBinRev(systemcode, binary); - for(i=0;i<=length;i++) { - if(binary[i]==1) { - x=i*2; - createLow(39-(x+1), 39-x); - } - } -} - -static void createUnit(int unit) { - int binary[255]; - int length = 0; - int i=0, x=0; - - length = decToBinRev(unit, binary); - for(i=0;i<=length;i++) { - if(binary[i]==1) { - x=i*2; - createLow(47-(x+1), 47-x); - } - } -} - -static void createState(int state) { - if(state == 0) { - createLow(40, 41); - } -} - - -static void createFooter(void) { - daycom->raw[48]=(AVG_PULSE_LENGTH); - daycom->raw[49]=(PULSE_DIV*AVG_PULSE_LENGTH); -} - -static int createCode(JsonNode *code) { - int id = -1; - int systemcode = -1; - int unit = -1; - int state = -1; - double itmp = -1; - - if(json_find_number(code, "id", &itmp) == 0) - id = (int)round(itmp); - if(json_find_number(code, "systemcode", &itmp) == 0) - systemcode = (int)round(itmp); - if(json_find_number(code, "unit", &itmp) == 0) - unit = (int)round(itmp); - if(json_find_number(code, "off", &itmp) == 0) - state=1; - if(json_find_number(code, "on", &itmp) == 0) - state=0; - - if(id == -1 || systemcode == -1 || unit == -1 || state == -1) { - logprintf(LOG_ERR, "daycom: insufficient number of arguments"); - return EXIT_FAILURE; - } else if(id > 63 || id < 0) { - logprintf(LOG_ERR, "daycom: invalid id range"); - return EXIT_FAILURE; - } else if(systemcode > 16999 || systemcode < 0) { - logprintf(LOG_ERR, "daycom: invalid systemcode range"); - return EXIT_FAILURE; - } else if(unit > 7 || unit < 0) { - logprintf(LOG_ERR, "daycom: invalid unit range"); - return EXIT_FAILURE; - } else { - createMessage(id, systemcode, unit, state); - clearCode(); - createId(id); - createSystemCode(systemcode); - createState(state); - createUnit(unit); - createFooter(); - daycom->rawlen = RAW_LENGTH; - state = 0; - } - return EXIT_SUCCESS; -} - -static void printHelp(void) { - printf("\t -i --id=id\t\t\tcontrol a device with this id\n"); - printf("\t -s --systemcode=systemcode\t\t\tcontrol a device with this systemcode\n"); - printf("\t -u --unitcode=unitcode\t\t\tcontrol a device with this unitcode\n"); - printf("\t -t --on\t\t\tsend an on signal\n"); - printf("\t -f --off\t\t\tsend an off signal\n"); -} - -#if !defined(MODULE) && !defined(_WIN32) -__attribute__((weak)) -#endif - -void daycomInit(void) { - protocol_register(&daycom); - protocol_set_id(daycom, "daycom"); - protocol_device_add(daycom, "daycom", "Daycom switches"); - daycom->devtype = SWITCH; - daycom->hwtype = RF433; - daycom->minrawlen = RAW_LENGTH; - daycom->maxrawlen = RAW_LENGTH; - daycom->maxgaplen = MAX_PULSE_LENGTH*PULSE_DIV; - daycom->mingaplen = MIN_PULSE_LENGTH*PULSE_DIV; - - options_add(&daycom->options, "t", "on", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); - options_add(&daycom->options, "f", "off", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); - options_add(&daycom->options, "u", "unit", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, "^([0-7])$"); - options_add(&daycom->options, "s", "systemcode", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, "^([0-9]{1,4}|1[0-6][0-9]{3})$"); - options_add(&daycom->options, "i", "id", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, "^[0-6]?[0-9]$"); - - options_add(&daycom->options, "0", "readonly", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)0, "^[10]{1}$"); - - daycom->parseCode=&parseCode; - daycom->createCode=&createCode; - daycom->printHelp=&printHelp; - daycom->validate=&validate; -} -#if defined(MODULE) && !defined(_WIN32) -void compatibility(struct module_t *module) { - module->name = "daycom"; - module->version = "1.1"; - module->reqversion = "6.0"; - module->reqcommit = "187"; -} - -void init(void) { - daycomInit(); -} -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/daycom.h b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/daycom.h deleted file mode 100644 index 8005a165..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/daycom.h +++ /dev/null @@ -1,27 +0,0 @@ -/* - Copyright (C) 2015 CurlyMo & Rafael - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#ifndef _PROTOCOL_DAYCOM_H_ -#define _PROTOCOL_DAYCOM_H_ - -#include "../protocol.h" - -struct protocol_t *daycom; -void daycomInit(void); - -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/ehome.c b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/ehome.c deleted file mode 100644 index f9bd8898..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/ehome.c +++ /dev/null @@ -1,220 +0,0 @@ -/* - Copyright (C) 2014 CurlyMo - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#include -#include -#include -#include - -#include "../../core/pilight.h" -#include "../../core/common.h" -#include "../../core/dso.h" -#include "../../core/log.h" -#include "../protocol.h" -#include "../../core/binary.h" -#include "../../core/gc.h" -#include "ehome.h" - -#define PULSE_MULTIPLIER 3 -#define MIN_PULSE_LENGTH 277 -#define MAX_PULSE_LENGTH 287 -#define AVG_PULSE_LENGTH 282 -#define RAW_LENGTH 50 - -static int validate(void) { - if(ehome->rawlen == RAW_LENGTH) { - if(ehome->raw[ehome->rawlen-1] >= (MIN_PULSE_LENGTH*PULSE_DIV) && - ehome->raw[ehome->rawlen-1] <= (MAX_PULSE_LENGTH*PULSE_DIV)) { - return 0; - } - } - - return -1; -} - -static void createMessage(int id, int state) { - ehome->message = json_mkobject(); - json_append_member(ehome->message, "id", json_mknumber(id, 0)); - if(state == 1) { - json_append_member(ehome->message, "state", json_mkstring("on")); - } else { - json_append_member(ehome->message, "state", json_mkstring("off")); - } -} - -static void parseCode(void) { - int i = 0, binary[RAW_LENGTH/4]; - - if(ehome->rawlen>RAW_LENGTH) { - logprintf(LOG_ERR, "ehome: parsecode - invalid parameter passed %d", ehome->rawlen); - return; - } - - for(i=0;irawlen-2;i+=4) { - if(ehome->raw[i+3] > (int)((double)AVG_PULSE_LENGTH*((double)PULSE_MULTIPLIER/2))) { - binary[i/4]=1; - } else { - binary[i/4]=0; - } - } - - int id = binToDec(binary, 1, 3); - int state = binary[0]; - - createMessage(id, state); -} - -static void createLow(int s, int e) { - int i; - - for(i=s;i<=e;i+=4) { - ehome->raw[i]=AVG_PULSE_LENGTH; - ehome->raw[i+1]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - ehome->raw[i+2]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - ehome->raw[i+3]=AVG_PULSE_LENGTH; - } -} - -static void createMed(int s, int e) { - int i; - - for(i=s;i<=e;i+=4) { - ehome->raw[i]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - ehome->raw[i+1]=AVG_PULSE_LENGTH; - ehome->raw[i+2]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - ehome->raw[i+3]=AVG_PULSE_LENGTH; - } -} - -static void createHigh(int s, int e) { - int i; - - for(i=s;i<=e;i+=4) { - ehome->raw[i]=AVG_PULSE_LENGTH; - ehome->raw[i+1]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - ehome->raw[i+2]=AVG_PULSE_LENGTH; - ehome->raw[i+3]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - } -} - -static void clearCode(void) { - createLow(0,47); -} - -static void createId(int id) { - int binary[255]; - int length = 0; - int i=0, x=0; - - length = decToBinRev(id, binary); - for(i=0;i<=length;i++) { - if(binary[i]==1) { - x=i*4; - createHigh(4+x, 4+(x+3)); - } - } -} - -static void createState(int state) { - if(state == 0) { - createMed(0, 3); - } else { - createHigh(0, 3); - } -} - -static void createFooter(void) { - ehome->raw[48]=(AVG_PULSE_LENGTH); - ehome->raw[49]=(PULSE_DIV*AVG_PULSE_LENGTH); -} - -static int createCode(struct JsonNode *code) { - int id = -1; - int state = -1; - double itmp = 0; - - if(json_find_number(code, "id", &itmp) == 0) - id = (int)round(itmp); - if(json_find_number(code, "off", &itmp) == 0) - state=0; - else if(json_find_number(code, "on", &itmp) == 0) - state=1; - - if(id == -1 || state == -1) { - logprintf(LOG_ERR, "ehome: insufficient number of arguments"); - return EXIT_FAILURE; - } else if(id > 7 || id < 0) { - logprintf(LOG_ERR, "ehome: invalid id range"); - return EXIT_FAILURE; - } else { - createMessage(id, state); - clearCode(); - createId(id); - createState(state); - createFooter(); - ehome->rawlen = RAW_LENGTH; - } - return EXIT_SUCCESS; -} - -static void printHelp(void) { - printf("\t -i --id=id\t\t\tcontrol a device with this id\n"); - printf("\t -t --on\t\t\tsend an on signal\n"); - printf("\t -f --off\t\t\tsend an off signal\n"); -} - -#if !defined(MODULE) && !defined(_WIN32) -__attribute__((weak)) -#endif -void ehomeInit(void) { - - protocol_register(&ehome); - protocol_set_id(ehome, "ehome"); - protocol_device_add(ehome, "ehome", "eHome Switches"); - ehome->devtype = SWITCH; - ehome->hwtype = RF433; - ehome->minrawlen = RAW_LENGTH; - ehome->maxrawlen = RAW_LENGTH; - ehome->maxgaplen = MAX_PULSE_LENGTH*PULSE_DIV; - ehome->mingaplen = MIN_PULSE_LENGTH*PULSE_DIV; - - options_add(&ehome->options, "i", "id", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, "^([0-4])$"); - options_add(&ehome->options, "t", "on", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); - options_add(&ehome->options, "f", "off", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); - - options_add(&ehome->options, "0", "readonly", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)0, "^[10]{1}$"); - options_add(&ehome->options, "0", "confirm", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)0, "^[10]{1}$"); - - ehome->parseCode=&parseCode; - ehome->createCode=&createCode; - ehome->printHelp=&printHelp; - ehome->validate=&validate; -} - -#if defined(MODULE) && !defined(_WIN32) -void compatibility(struct module_t *module) { - module->name = "ehome"; - module->version = "1.1"; - module->reqversion = "6.0"; - module->reqcommit = "84"; -} - -void init(void) { - ehomeInit(); -} -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/ehome.h b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/ehome.h deleted file mode 100644 index ca50757e..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/ehome.h +++ /dev/null @@ -1,27 +0,0 @@ -/* - Copyright (C) 2014 CurlyMo - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#ifndef _PROTOCOL_EHOME_H_ -#define _PROTOCOL_EHOME_H_ - -#include "../protocol.h" - -struct protocol_t *ehome; -void ehomeInit(void); - -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/elro_300_switch.c b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/elro_300_switch.c deleted file mode 100644 index 16d3daea..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/elro_300_switch.c +++ /dev/null @@ -1,367 +0,0 @@ -/* - Copyright (C) 2014 CurlyMo - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#include -#include -#include -#include - -#include "../../core/pilight.h" -#include "../../core/common.h" -#include "../../core/dso.h" -#include "../../core/log.h" -#include "../protocol.h" -#include "../../core/binary.h" -#include "../../core/gc.h" -#include "elro_300_switch.h" - -#define PULSE_MULTIPLIER 4 -#define MIN_PULSE_LENGTH 297 -#define MAX_PULSE_LENGTH 307 -#define AVG_PULSE_LENGTH 302 -#define RAW_LENGTH 116 - -static int validate(void) { - if(elro_300_switch->rawlen == RAW_LENGTH) { - if(elro_300_switch->raw[elro_300_switch->rawlen-1] >= (MIN_PULSE_LENGTH*PULSE_DIV) && - elro_300_switch->raw[elro_300_switch->rawlen-1] <= (MAX_PULSE_LENGTH*PULSE_DIV)) { - return 0; - } - } - - return -1; -} - -/** - * Creates as System message informing the daemon about a received or created message - * - * systemcode : integer number, the 32 bit system code - * unitcode : unit being adressed, integer number - * state : either 2 (off) or 1 (on) - * group : if 1 this affects a whole group of devices - */ -static void createMessage(unsigned long long systemcode, int unitcode, int state, int group) { - elro_300_switch->message = json_mkobject(); - //aka address - json_append_member(elro_300_switch->message, "systemcode", json_mknumber((double)systemcode, 0)); - //toggle all or just one unit - if(group == 1) { - json_append_member(elro_300_switch->message, "all", json_mknumber(group, 0)); - } else { - json_append_member(elro_300_switch->message, "unitcode", json_mknumber(unitcode, 0)); - } - //aka command - if(state == 1) { - json_append_member(elro_300_switch->message, "state", json_mkstring("on")); - } - else if(state == 2) { - json_append_member(elro_300_switch->message, "state", json_mkstring("off")); - } -} - -/** - * This is the main method when reading a received code - * Decodes the received stream - * - */ -static void parseCode(void) { - int i = 0, x = 0, binary[RAW_LENGTH/2]; - - if(elro_300_switch->rawlen>RAW_LENGTH) { - logprintf(LOG_ERR, "elro_300_switch: parsecode - invalid parameter passed %d", elro_300_switch->rawlen); - return; - } - - //utilize the "code" field - //at this point the code field holds translated "0" and "1" codes from the received pulses - //this means that we have to combine these ourselves into meaningful values in groups of 2 - - for(i=0; i < elro_300_switch->rawlen; i++) { - if(elro_300_switch->raw[i] > (int)((double)AVG_PULSE_LENGTH*((double)PULSE_MULTIPLIER/2))) { - if(i&1) { - binary[x++] = 1; - } else { - return; // even pulse lengths must be low - } - } else if(i&1) { - binary[x++] = 0; - } - } - - //chunked code now contains "groups of 2" codes for us to handle. - unsigned long long systemcode = binToDecRevUl(binary, 11, 42); - int groupcode = binToDec(binary, 43, 46); - int groupcode2 = binToDec(binary, 49, 50); - int unitcode = binToDec(binary, 51, 56); - int state = binToDec(binary, 47, 48); - int groupRes = 0; - - if(groupcode == 13 && groupcode2 == 2) { - groupRes = 0; - } else if(groupcode == 3 && groupcode2 == 3) { - groupRes = 1; - } else { - return; - } - if(state < 1 || state > 2) { - return; - } else { - createMessage(systemcode, unitcode, state, groupRes); - } -} - -/** - * Creates a number of "low" entries (302 302). Note that each entry requires 2 raw positions - * so e-s should be a multiple of 2 - * s : start position in the raw code (inclusive) - * e : end position in the raw code (inclusive) - */ -static void createLow(int s, int e) { - int i; - - for(i=s;i<=e;i+=2) { - elro_300_switch->raw[i]=(AVG_PULSE_LENGTH); - elro_300_switch->raw[i+1]=(AVG_PULSE_LENGTH); - } -} - -/** - * Creates a number of "high" entries (302 1028). Note that each entry requires 2 raw positions - * so e-s should be a multiple of 2 - * s : start position in the raw code (inclusive) - * e : end position in the raw code (inclusive) - */ -static void createHigh(int s, int e) { - int i; - - for(i=s;i<=e;i+=2) { - elro_300_switch->raw[i]=(AVG_PULSE_LENGTH); - elro_300_switch->raw[i+1]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - } -} - -/** - * This simply clears the full length of the code to be all "zeroes" (LOW entries) - */ -static void elro300ClearCode(void) { - createLow(0,116); -} - -/** - * Takes the passed number - * converts it into raw and inserts them into the raw code at the appropriate position - * - * systemcode : unsigned integer number, the 32 bit system code - */ -static void createSystemCode(unsigned long long systemcode) { - int binary[255]; - int length = 0; - int i=0, x=0; - length = decToBinRevUl(systemcode, binary); - for(i=0;i<=length;i++) { - if(binary[(length)-i]==1) { - x=i*2; - createHigh(22+x, 22+x+1); - } - } -} - -/** - * Takes the passed number converts it into raw and inserts it into the raw code at the appropriate position - * - * unitcode : integer number, id of the unit to control - */ -static void createUnitCode(int unitcode) { - int binary[255]; - int length = 0; - int i=0, x=0; - - length = decToBinRev(unitcode, binary); - for(i=0;i<=length;i++) { - if(binary[i]==1) { - x=i*2; - createHigh(102+x, 102+x+1); - } - } -} - -/** - * Takes the passed number converts it into raw and inserts it into the raw code at the appropriate position - * - * state : integer number, state value to set. can be either 1 (on) or 2 (off) - */ -static void createState(int state) { - if(state == 1) { - createHigh(94, 95); - createLow(96, 97); - } - else { - createLow(94, 95); - createHigh(96, 97); - } -} - -/** - * sets the first group code portions to the appropriate raw values. - * Fro grouped mode this is the equivalent to 1100 and 11, for non-grouped mode 1011 and 01 - * - * group : integer value, 1 means grouped enabled, 0 means disabled - */ -static void createGroupCode(int group) { - if(group == 1) { - createHigh(86, 89); - createLow(90, 93); - createHigh(98, 101); - } else { - createHigh(86, 87); - createLow(88, 89); - createHigh(90, 93); - createLow(98, 99); - createHigh(100, 101); - } -} - -/** - * Inserts the (as far as is known) fixed message preamble - * First eleven words are the preamble - */ -static void createPreamble(void) { - createHigh(0,3); - createLow(4,9); - createHigh(10,17); - createLow(18,21); -} - -/** - * Inserts the message trailer (one HIGH) into the raw message - */ -static void createFooter(void) { - elro_300_switch->raw[114]=(AVG_PULSE_LENGTH); - elro_300_switch->raw[115]=(PULSE_DIV*AVG_PULSE_LENGTH); -} - - -/** - * Main method for creating a message based on daemon-passed values in the elro_300_switch protocol. - * code : JSON Message containing the received parameters to use for message creation - * - * returns : EXIT_SUCCESS or EXIT_FAILURE on obvious occasions - */ -static int createCode(struct JsonNode *code) { - unsigned long long systemcode = 0; - int unitcode = -1; - int group = 0; - int state = -1; - double itmp; - - if(json_find_number(code, "systemcode", &itmp) == 0) { - systemcode = (unsigned long long)itmp; - } - if(json_find_number(code, "unitcode", &itmp) == 0) { - unitcode = (int)round(itmp); - } - if(json_find_number(code, "all", &itmp) == 0) { - group = 1; - //on the reference remote, group toggles always used a unit code of 56. - //for that reason we are enforcing that here - unitcode = 56; - } - - if(json_find_number(code, "off", &itmp) == 0) { - state=2; - } - else if(json_find_number(code, "on", &itmp) == 0) { - state=1; - } - - if(systemcode == 0 || unitcode == -1 || state == -1) { - logprintf(LOG_ERR, "elro_300_switch: insufficient number of arguments"); - return EXIT_FAILURE; - } else if(systemcode > 4294967295u || unitcode > 99 || unitcode < 0) { - logprintf(LOG_ERR, "elro_300_switch: values out of valid range"); - } else { - createMessage(systemcode, unitcode, state, group); - elro300ClearCode(); - createPreamble(); - createSystemCode(systemcode); - createGroupCode(group); - createState(state); - createUnitCode(unitcode); - createFooter(); - elro_300_switch->rawlen = RAW_LENGTH; - } - return EXIT_SUCCESS; -} - -/** - * Outputs help messages directly to the current output target (probably the console) - */ -static void printHelp(void) { - printf("\t -s --systemcode=systemcode\tcontrol a device with this systemcode\n"); - printf("\t -a --all\t\t\ttoggle switching all devices on or off\n"); - printf("\t -u --unitcode=unitcode\t\tcontrol a device with this unitcode\n"); - printf("\t -t --on\t\t\tsend an on signal\n"); - printf("\t -f --off\t\t\tsend an off signal\n"); -} - -/** - * Main Init method called to init the protocol and register its functions with pilight - */ -#if !defined(MODULE) && !defined(_WIN32) -__attribute__((weak)) -#endif -void elro300SwitchInit(void) { - - protocol_register(&elro_300_switch); - protocol_set_id(elro_300_switch, "elro_300_switch"); - protocol_device_add(elro_300_switch, "elro_300_switch", "Elro 300 Series Switches"); - elro_300_switch->devtype = SWITCH; - elro_300_switch->hwtype = RF433; - elro_300_switch->minrawlen = RAW_LENGTH; - elro_300_switch->maxrawlen = RAW_LENGTH; - elro_300_switch->maxgaplen = MAX_PULSE_LENGTH*PULSE_DIV; - elro_300_switch->mingaplen = MIN_PULSE_LENGTH*PULSE_DIV; - - options_add(&elro_300_switch->options, "s", "systemcode", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, "^([0-9]{1,9}|[1-3][0-9]{9}|4([01][0-9]{8}|2([0-8][0-9]{7}|9([0-3][0-9]{6}|4([0-8][0-9]{5}|9([0-5][0-9]{4}|6([0-6][0-9]{3}|7([01][0-9]{2}|2([0-8][0-9]|9[0-4])))))))))$"); - options_add(&elro_300_switch->options, "u", "unitcode", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, "^[0-9]{1,2}$"); - options_add(&elro_300_switch->options, "t", "on", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); - options_add(&elro_300_switch->options, "f", "off", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); - options_add(&elro_300_switch->options, "a", "all", OPTION_OPT_VALUE, DEVICES_OPTIONAL, JSON_NUMBER, NULL, NULL); - - options_add(&elro_300_switch->options, "0", "readonly", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)0, "^[10]{1}$"); - options_add(&elro_300_switch->options, "0", "confirm", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)0, "^[10]{1}$"); - - - elro_300_switch->parseCode=&parseCode; - elro_300_switch->createCode=&createCode; - elro_300_switch->printHelp=&printHelp; - elro_300_switch->validate=&validate; -} - -#if defined(MODULE) && !defined(_WIN32) -void compatibility(struct module_t *module) { - module->name = "elro_300_switch"; - module->version = "2.3"; - module->reqversion = "6.0"; - module->reqcommit = "84"; -} - -void init(void) { - elro300SwitchInit(); -} -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/elro_300_switch.h b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/elro_300_switch.h deleted file mode 100644 index 464903a9..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/elro_300_switch.h +++ /dev/null @@ -1,27 +0,0 @@ -/* - Copyright (C) 2013 CurlyMo - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#ifndef _PROTOCOL_ELRO_300_SWITCH_H_ -#define _PROTOCOL_ELRO_300_SWITCH_H_ - -#include "../protocol.h" - -struct protocol_t *elro_300_switch; -void elro300SwitchInit(void); - -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/elro_400_switch.c b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/elro_400_switch.c deleted file mode 100644 index 143cddfb..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/elro_400_switch.c +++ /dev/null @@ -1,233 +0,0 @@ -/* - Copyright (C) 2013 CurlyMo - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#include -#include -#include -#include - -#include "../../core/pilight.h" -#include "../../core/common.h" -#include "../../core/dso.h" -#include "../../core/log.h" -#include "../protocol.h" -#include "../../core/binary.h" -#include "../../core/gc.h" -#include "elro_400_switch.h" - -#define PULSE_MULTIPLIER 3 -#define MIN_PULSE_LENGTH 291 -#define MAX_PULSE_LENGTH 301 -#define AVG_PULSE_LENGTH 296 -#define RAW_LENGTH 50 - -static int validate(void) { - if(elro_400_switch->rawlen == RAW_LENGTH) { - if(elro_400_switch->raw[elro_400_switch->rawlen-1] >= (MIN_PULSE_LENGTH*PULSE_DIV) && - elro_400_switch->raw[elro_400_switch->rawlen-1] <= (MAX_PULSE_LENGTH*PULSE_DIV)) { - return 0; - } - } - - return -1; -} - -static void createMessage(int systemcode, int unitcode, int state) { - elro_400_switch->message = json_mkobject(); - json_append_member(elro_400_switch->message, "systemcode", json_mknumber(systemcode, 0)); - json_append_member(elro_400_switch->message, "unitcode", json_mknumber(unitcode, 0)); - if(state == 1) { - json_append_member(elro_400_switch->message, "state", json_mkstring("on")); - } else { - json_append_member(elro_400_switch->message, "state", json_mkstring("off")); - } -} - -static void parseCode(void) { - int x = 0, i = 0, binary[RAW_LENGTH/4]; - - if(elro_400_switch->rawlen>RAW_LENGTH) { - logprintf(LOG_ERR, "elro_400_switch: parsecode - invalid parameter passed %d", elro_400_switch->rawlen); - return; - } - - for(x=0;xrawlen-2;x+=4) { - if(elro_400_switch->raw[x+3] > (int)((double)AVG_PULSE_LENGTH*((double)PULSE_MULTIPLIER/2))) { - binary[i++] = 0; - } else { - binary[i++] = 1; - } - } - - int systemcode = binToDecRev(binary, 0, 4); - int unitcode = binToDecRev(binary, 5, 9); - int state = binary[11]; - createMessage(systemcode, unitcode, state); -} - -static void createLow(int s, int e) { - int i; - - for(i=s;i<=e;i+=4) { - elro_400_switch->raw[i]=(AVG_PULSE_LENGTH); - elro_400_switch->raw[i+1]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - elro_400_switch->raw[i+2]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - elro_400_switch->raw[i+3]=(AVG_PULSE_LENGTH); - } -} - -static void createHigh(int s, int e) { - int i; - - for(i=s;i<=e;i+=4) { - elro_400_switch->raw[i]=(AVG_PULSE_LENGTH); - elro_400_switch->raw[i+1]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - elro_400_switch->raw[i+2]=(AVG_PULSE_LENGTH); - elro_400_switch->raw[i+3]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - } -} -static void clearCode(void) { - createHigh(0,47); -} - -static void createSystemCode(int systemcode) { - int binary[255]; - int length = 0; - int i=0, x=0; - - length = decToBinRev(systemcode, binary); - for(i=0;i<=length;i++) { - if(binary[i]==1) { - x=i*4; - createLow(19-(x+3), 19-x); - } - } -} - -static void createUnitCode(int unitcode) { - int binary[255]; - int length = 0; - int i=0, x=0; - - length = decToBinRev(unitcode, binary); - for(i=0;i<=length;i++) { - if(binary[i]==1) { - x=i*4; - createLow(39-(x+3), 39-x); - } - } -} - -static void createState(int state) { - if(state == 1) { - createLow(44, 47); - createLow(40, 43); - } else { - createLow(40, 43); - } -} - -static void createFooter(void) { - elro_400_switch->raw[48]=(AVG_PULSE_LENGTH); - elro_400_switch->raw[49]=(PULSE_DIV*AVG_PULSE_LENGTH); -} - -static int createCode(struct JsonNode *code) { - int systemcode = -1; - int unitcode = -1; - int state = -1; - double itmp = 0; - - if(json_find_number(code, "systemcode", &itmp) == 0) - systemcode = (int)round(itmp); - if(json_find_number(code, "unitcode", &itmp) == 0) - unitcode = (int)round(itmp); - if(json_find_number(code, "off", &itmp) == 0) - state=0; - else if(json_find_number(code, "on", &itmp) == 0) - state=1; - - if(systemcode == -1 || unitcode == -1 || state == -1) { - logprintf(LOG_ERR, "elro_400_switch: insufficient number of arguments"); - return EXIT_FAILURE; - } else if(systemcode > 31 || systemcode < 0) { - logprintf(LOG_ERR, "elro_400_switch: invalid systemcode range"); - return EXIT_FAILURE; - } else if(unitcode > 31 || unitcode < 0) { - logprintf(LOG_ERR, "elro_400_switch: invalid unitcode range"); - return EXIT_FAILURE; - } else { - createMessage(systemcode, unitcode, state); - clearCode(); - createSystemCode(systemcode); - createUnitCode(unitcode); - createState(state); - createFooter(); - elro_400_switch->rawlen = RAW_LENGTH; - } - return EXIT_SUCCESS; -} - -static void printHelp(void) { - printf("\t -s --systemcode=systemcode\tcontrol a device with this systemcode\n"); - printf("\t -u --unitcode=unitcode\t\tcontrol a device with this unitcode\n"); - printf("\t -t --on\t\t\tsend an on signal\n"); - printf("\t -f --off\t\t\tsend an off signal\n"); -} - -#if !defined(MODULE) && !defined(_WIN32) -__attribute__((weak)) -#endif -void elro400SwitchInit(void) { - - protocol_register(&elro_400_switch); - protocol_set_id(elro_400_switch, "elro_400_switch"); - protocol_device_add(elro_400_switch, "elro_400_switch", "Elro 400 Series Switches"); - elro_400_switch->devtype = SWITCH; - elro_400_switch->hwtype = RF433; - elro_400_switch->minrawlen = RAW_LENGTH; - elro_400_switch->maxrawlen = RAW_LENGTH; - elro_400_switch->maxgaplen = MAX_PULSE_LENGTH*PULSE_DIV; - elro_400_switch->mingaplen = MIN_PULSE_LENGTH*PULSE_DIV; - - options_add(&elro_400_switch->options, "s", "systemcode", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, "^(3[012]?|[012][0-9]|[0-9]{1})$"); - options_add(&elro_400_switch->options, "u", "unitcode", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, "^(3[012]?|[012][0-9]|[0-9]{1})$"); - options_add(&elro_400_switch->options, "t", "on", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); - options_add(&elro_400_switch->options, "f", "off", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); - - options_add(&elro_400_switch->options, "0", "readonly", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)0, "^[10]{1}$"); - options_add(&elro_400_switch->options, "0", "confirm", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)0, "^[10]{1}$"); - - elro_400_switch->parseCode=&parseCode; - elro_400_switch->createCode=&createCode; - elro_400_switch->printHelp=&printHelp; - elro_400_switch->validate=&validate; -} - -#if defined(MODULE) && !defined(_WIN32) -void compatibility(struct module_t *module) { - module->name = "elro_400_switch"; - module->version = "2.4"; - module->reqversion = "6.0"; - module->reqcommit = "84"; -} - -void init(void) { - elro400SwitchInit(); -} -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/elro_400_switch.h b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/elro_400_switch.h deleted file mode 100644 index 82679c97..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/elro_400_switch.h +++ /dev/null @@ -1,27 +0,0 @@ -/* - Copyright (C) 2013 CurlyMo - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#ifndef _PROTOCOL_ELRO_400_SWITCH_H_ -#define _PROTOCOL_ELRO_400_SWITCH_H_ - -#include "../protocol.h" - -struct protocol_t *elro_400_switch; -void elro400SwitchInit(void); - -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/elro_800_contact.c b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/elro_800_contact.c deleted file mode 100644 index b5fa8653..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/elro_800_contact.c +++ /dev/null @@ -1,118 +0,0 @@ -/* - Copyright (C) 2014 CurlyMo - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#include -#include -#include -#include - -#include "../../core/pilight.h" -#include "../../core/common.h" -#include "../../core/dso.h" -#include "../../core/log.h" -#include "../protocol.h" -#include "../../core/binary.h" -#include "../../core/gc.h" -#include "elro_800_contact.h" - -#define PULSE_MULTIPLIER 3 -#define MIN_PULSE_LENGTH 283 -#define MAX_PULSE_LENGTH 305 -#define AVG_PULSE_LENGTH 300 -#define RAW_LENGTH 50 - -static int validate(void) { - if(elro_800_contact->rawlen == RAW_LENGTH) { - if(elro_800_contact->raw[elro_800_contact->rawlen-1] >= (MIN_PULSE_LENGTH*PULSE_DIV) && - elro_800_contact->raw[elro_800_contact->rawlen-1] <= (MAX_PULSE_LENGTH*PULSE_DIV)) { - return 0; - } - } - - return -1; -} - -static void createMessage(int systemcode, int unitcode, int state) { - elro_800_contact->message = json_mkobject(); - json_append_member(elro_800_contact->message, "systemcode", json_mknumber(systemcode, 0)); - json_append_member(elro_800_contact->message, "unitcode", json_mknumber(unitcode, 0)); - if(state == 0) { - json_append_member(elro_800_contact->message, "state", json_mkstring("opened")); - } else { - json_append_member(elro_800_contact->message, "state", json_mkstring("closed")); - } -} - -static void parseCode(void) { - int binary[RAW_LENGTH/4], x = 0, i = 0; - - if(elro_800_contact->rawlen>RAW_LENGTH) { - logprintf(LOG_ERR, "elro_800_contact: parsecode - invalid parameter passed %d", elro_800_contact->rawlen); - return; - } - - for(x=0;xrawlen-2;x+=4) { - if(elro_800_contact->raw[x+3] > (int)((double)AVG_PULSE_LENGTH*((double)PULSE_MULTIPLIER/2))) { - binary[i++] = 1; - } else { - binary[i++] = 0; - } - } - - int systemcode = binToDec(binary, 0, 4); - int unitcode = binToDec(binary, 5, 9); - int state = binary[11]; - createMessage(systemcode, unitcode, state); -} - -#if !defined(MODULE) && !defined(_WIN32) -__attribute__((weak)) -#endif -void elro800ContactInit(void) { - - protocol_register(&elro_800_contact); - protocol_set_id(elro_800_contact, "elro_800_contact"); - protocol_device_add(elro_800_contact, "elro_800_contact", "Elro Series 800 Contact"); - elro_800_contact->devtype = CONTACT; - elro_800_contact->hwtype = RF433; - elro_800_contact->minrawlen = RAW_LENGTH; - elro_800_contact->maxrawlen = RAW_LENGTH; - elro_800_contact->maxgaplen = MAX_PULSE_LENGTH*PULSE_DIV; - elro_800_contact->mingaplen = MIN_PULSE_LENGTH*PULSE_DIV; - - options_add(&elro_800_contact->options, "s", "systemcode", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, "^(3[012]?|[012][0-9]|[0-9]{1})$"); - options_add(&elro_800_contact->options, "u", "unitcode", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, "^(3[012]?|[012][0-9]|[0-9]{1})$"); - options_add(&elro_800_contact->options, "t", "opened", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); - options_add(&elro_800_contact->options, "f", "closed", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); - - elro_800_contact->parseCode=&parseCode; - elro_800_contact->validate=&validate; -} - -#if defined(MODULE) && !defined(_WIN32) -void compatibility(struct module_t *module) { - module->name = "elro_800_contact"; - module->version = "2.4"; - module->reqversion = "6.0"; - module->reqcommit = "84"; -} - -void init(void) { - elro800ContactInit(); -} -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/elro_800_contact.h b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/elro_800_contact.h deleted file mode 100644 index 841986a3..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/elro_800_contact.h +++ /dev/null @@ -1,27 +0,0 @@ -/* - Copyright (C) 2013 CurlyMo - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#ifndef _PROTOCOL_ELRO_800_CONTACT_H_ -#define _PROTOCOL_ELRO_800_CONTACT_H_ - -#include "../protocol.h" - -struct protocol_t *elro_800_contact; -void elro800ContactInit(void); - -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/elro_800_switch.c b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/elro_800_switch.c deleted file mode 100644 index 82ea55e7..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/elro_800_switch.c +++ /dev/null @@ -1,269 +0,0 @@ -/* - Copyright (C) 2014 CurlyMo - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#include -#include -#include -#include - -#include "../../core/pilight.h" -#include "../../core/common.h" -#include "../../core/dso.h" -#include "../../core/log.h" -#include "../protocol.h" -#include "../../core/binary.h" -#include "../../core/gc.h" -#include "elro_800_switch.h" - -#define PULSE_MULTIPLIER 3 -#define MIN_PULSE_LENGTH 274 -#define MAX_PULSE_LENGTH 320 -#define AVG_PULSE_LENGTH 300 -#define RAW_LENGTH 50 - -static int validate(void) { - if(elro_800_switch->rawlen == RAW_LENGTH) { - if(elro_800_switch->raw[elro_800_switch->rawlen-1] >= (MIN_PULSE_LENGTH*PULSE_DIV) && - elro_800_switch->raw[elro_800_switch->rawlen-1] <= (MAX_PULSE_LENGTH*PULSE_DIV)) { - return 0; - } - } - - return -1; -} - -static void createMessage(int systemcode, int unitcode, int state) { - elro_800_switch->message = json_mkobject(); - json_append_member(elro_800_switch->message, "systemcode", json_mknumber(systemcode, 0)); - json_append_member(elro_800_switch->message, "unitcode", json_mknumber(unitcode, 0)); - if(state == 0) { - json_append_member(elro_800_switch->message, "state", json_mkstring("on")); - } else { - json_append_member(elro_800_switch->message, "state", json_mkstring("off")); - } -} - -static void parseCode(void) { - int binary[RAW_LENGTH/4], x = 0; - - if(elro_800_switch->rawlen>RAW_LENGTH) { - logprintf(LOG_ERR, "elro_800_switch: parsecode - invalid parameter passed %d", elro_800_switch->rawlen); - return; - } - - for(x=0;xrawlen-2;x+=4) { - if(elro_800_switch->raw[x+3] > (int)((double)AVG_PULSE_LENGTH*((double)PULSE_MULTIPLIER/2))) { - binary[x/4] = 1; - } else { - binary[x/4] = 0; - } - } - - int systemcode = binToDec(binary, 0, 4); - int unitcode = binToDec(binary, 5, 9); - int check = binary[10]; - int state = binary[11]; - - // second part of systemcode based on Med - for(x=0;x<=16;x+=4) { - if(elro_800_switch->raw[x+0] > (int)((double)AVG_PULSE_LENGTH*((double)PULSE_MULTIPLIER/2))) { - binary[x/4] = 1; - } else { - binary[x/4] = 0; - } - } - int systemcode2 = binToDec(binary, 0, 4); - - systemcode |= (systemcode2<<5); - - if(check != state) { - createMessage(systemcode, unitcode, state); - } -} - -static void createLow(int s, int e) { - int i; - - for(i=s;i<=e;i+=4) { - elro_800_switch->raw[i]=(AVG_PULSE_LENGTH); - elro_800_switch->raw[i+1]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - elro_800_switch->raw[i+2]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - elro_800_switch->raw[i+3]=(AVG_PULSE_LENGTH); - } -} - -static void createMed(int s, int e) { - int i; - - for(i=s;i<=e;i+=4) { - elro_800_switch->raw[i]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - elro_800_switch->raw[i+1]=(AVG_PULSE_LENGTH); - elro_800_switch->raw[i+2]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - elro_800_switch->raw[i+3]=(AVG_PULSE_LENGTH); - } -} - -static void createHigh(int s, int e) { - int i; - - for(i=s;i<=e;i+=4) { - elro_800_switch->raw[i]=(AVG_PULSE_LENGTH); - elro_800_switch->raw[i+1]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - elro_800_switch->raw[i+2]=(AVG_PULSE_LENGTH); - elro_800_switch->raw[i+3]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - } -} -static void clearCode(void) { - createLow(0,47); -} - -static void createSystemCode(int systemcode) { - int binary[255]; - int length = 0; - int i=0, x=0; - - length = decToBinRev(systemcode & 0x1F, binary); - for(i=0;i<=length;i++) { - if(binary[i]==1) { - x=i*4; - createHigh(x, x+3); - } - } - - length = decToBinRev((systemcode>>5) & 0x1F, binary); - for(i=0;i<=length;i++) { - if(binary[i]==1) { - x=i*4; - createMed(x, x+3); - } - } -} - -static void createUnitCode(int unitcode) { - int binary[255]; - int length = 0; - int i=0, x=0; - - length = decToBinRev(unitcode, binary); - for(i=0;i<=length;i++) { - if(binary[i]==1) { - x=i*4; - createHigh(20+x, 20+x+3); - } - } -} - -static void createState(int state) { - if(state == 1) { - createHigh(44, 47); - } else { - createHigh(40, 43); - } -} - -static void createFooter(void) { - elro_800_switch->raw[48]=(AVG_PULSE_LENGTH); - elro_800_switch->raw[49]=(PULSE_DIV*AVG_PULSE_LENGTH); -} - -static int createCode(struct JsonNode *code) { - int systemcode = -1; - int unitcode = -1; - int state = -1; - double itmp = 0; - - if(json_find_number(code, "systemcode", &itmp) == 0) - systemcode = (int)round(itmp); - if(json_find_number(code, "unitcode", &itmp) == 0) - unitcode = (int)round(itmp); - if(json_find_number(code, "off", &itmp) == 0) - state=1; - else if(json_find_number(code, "on", &itmp) == 0) - state=0; - - if(systemcode == -1 || unitcode == -1 || state == -1) { - logprintf(LOG_ERR, "elro_800_switch: insufficient number of arguments"); - return EXIT_FAILURE; - } else if(systemcode > 1023 || systemcode < 0) { - logprintf(LOG_ERR, "elro_800_switch: invalid systemcode range"); - return EXIT_FAILURE; - } else if(unitcode > 31 || unitcode < 0) { - logprintf(LOG_ERR, "elro_800_switch: invalid unitcode range"); - return EXIT_FAILURE; - } else { - createMessage(systemcode, unitcode, state); - clearCode(); - createSystemCode(systemcode); - createUnitCode(unitcode); - createState(state); - createFooter(); - elro_800_switch->rawlen = RAW_LENGTH; - } - return EXIT_SUCCESS; -} - -static void printHelp(void) { - printf("\t -s --systemcode=systemcode\tcontrol a device with this systemcode\n"); - printf("\t -u --unitcode=unitcode\t\tcontrol a device with this unitcode\n"); - printf("\t -t --on\t\t\tsend an on signal\n"); - printf("\t -f --off\t\t\tsend an off signal\n"); -} - -#if !defined(MODULE) && !defined(_WIN32) -__attribute__((weak)) -#endif -void elro800SwitchInit(void) { - - protocol_register(&elro_800_switch); - protocol_set_id(elro_800_switch, "elro_800_switch"); - protocol_device_add(elro_800_switch, "elro_800_switch", "Elro 800 series Switches"); - protocol_device_add(elro_800_switch, "brennenstuhl", "Brennenstuhl Comfort"); - protocol_device_add(elro_800_switch, "maxitronic", "Maxi-Tronic FUNK-LIGHT switches"); - elro_800_switch->devtype = SWITCH; - elro_800_switch->hwtype = RF433; - elro_800_switch->minrawlen = RAW_LENGTH; - elro_800_switch->maxrawlen = RAW_LENGTH; - elro_800_switch->maxgaplen = MAX_PULSE_LENGTH*PULSE_DIV; - elro_800_switch->mingaplen = MIN_PULSE_LENGTH*PULSE_DIV; - - options_add(&elro_800_switch->options, "s", "systemcode", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, "^102[0-3]|10[01][0-9]|[0-9]{1,3}$"); - options_add(&elro_800_switch->options, "u", "unitcode", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, "^(3[012]?|[012][0-9]|[0-9]{1})$"); - options_add(&elro_800_switch->options, "t", "on", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); - options_add(&elro_800_switch->options, "f", "off", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); - - options_add(&elro_800_switch->options, "0", "readonly", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)0, "^[10]{1}$"); - options_add(&elro_800_switch->options, "0", "confirm", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)0, "^[10]{1}$"); - - elro_800_switch->parseCode=&parseCode; - elro_800_switch->createCode=&createCode; - elro_800_switch->printHelp=&printHelp; - elro_800_switch->validate=&validate; -} - -#if defined(MODULE) && !defined(_WIN32) -void compatibility(struct module_t *module) { - module->name = "elro_800_switch"; - module->version = "2.5"; - module->reqversion = "6.0"; - module->reqcommit = "84"; -} - -void init(void) { - elro800SwitchInit(); -} -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/elro_800_switch.h b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/elro_800_switch.h deleted file mode 100644 index b31eb90c..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/elro_800_switch.h +++ /dev/null @@ -1,27 +0,0 @@ -/* - Copyright (C) 2013 CurlyMo - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#ifndef _PROTOCOL_ELRO_800_SWITCH_H_ -#define _PROTOCOL_ELRO_800_SWITCH_H_ - -#include "../protocol.h" - -struct protocol_t *elro_800_switch; -void elro800SwitchInit(void); - -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/eurodomest_switch.c b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/eurodomest_switch.c deleted file mode 100644 index de8dd437..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/eurodomest_switch.c +++ /dev/null @@ -1,368 +0,0 @@ -/* - Copyright (C) 2015 woutput - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#include -#include -#include -#include - -#include "../../core/pilight.h" -#include "../../core/common.h" -#include "../../core/dso.h" -#include "../../core/log.h" -#include "../protocol.h" -#include "../../core/binary.h" -#include "../../core/gc.h" -#include "eurodomest_switch.h" - -// Timing from http://forum.pilight.org/attachment.php?aid=595 - -// Increase this value to be more robust, but also create more false positives -#define PEAK_TO_PEAK_JITTER 200 - -// About 2/3 of the jitter appears to make the pulses longer instead of shorter -// The same jitter appears on every pulse type (as may be expected) - -// Short pulse timing -#define MIN_SHORT_PULSE_LENGTH (AVG_SHORT_PULSE_LENGTH - 0.333 * PEAK_TO_PEAK_JITTER) -#define AVG_SHORT_PULSE_LENGTH 280 -#define MAX_SHORT_PULSE_LENGTH (AVG_SHORT_PULSE_LENGTH + 0.667 * PEAK_TO_PEAK_JITTER) - -// Medium pulse timing -#define MIN_MEDIUM_PULSE_LENGTH (AVG_MEDIUM_PULSE_LENGTH - 0.333 * PEAK_TO_PEAK_JITTER) -#define AVG_MEDIUM_PULSE_LENGTH 868 -#define MAX_MEDIUM_PULSE_LENGTH (AVG_MEDIUM_PULSE_LENGTH + 0.667 * PEAK_TO_PEAK_JITTER) - -// Long pulse timing -#define MIN_LONG_PULSE_LENGTH (AVG_LONG_PULSE_LENGTH - 0.333 * PEAK_TO_PEAK_JITTER) -#define AVG_LONG_PULSE_LENGTH 9660 -#define MAX_LONG_PULSE_LENGTH (AVG_LONG_PULSE_LENGTH + 0.667 * PEAK_TO_PEAK_JITTER) - -#define RAW_LENGTH 50 -// Two pulses per bit, last two pulses are footer -#define BINARY_LENGTH 24 - -#define LEARN_REPEATS 40 -#define NORMAL_REPEATS 10 - -static int validate(void) { - if (eurodomest_switch->rawlen == RAW_LENGTH) { - if (eurodomest_switch->raw[eurodomest_switch->rawlen - 1] >= MIN_LONG_PULSE_LENGTH && - eurodomest_switch->raw[eurodomest_switch->rawlen - 1] <= MAX_LONG_PULSE_LENGTH) { - return 0; - } - } - - return -1; -} - -static void createMessage(int id, int unit, int state, int all, int learn) { - eurodomest_switch->message = json_mkobject(); - - json_append_member(eurodomest_switch->message, "id", json_mknumber(id, 0)); - - if (all == 1) { - json_append_member(eurodomest_switch->message, "all", json_mknumber(all, 0)); - } else { - json_append_member(eurodomest_switch->message, "unit", json_mknumber(unit, 0)); - } - - if (state == 1) { - json_append_member(eurodomest_switch->message, "state", json_mkstring("on")); - } else { - json_append_member(eurodomest_switch->message, "state", json_mkstring("off")); - } - - if (learn == 1) { - eurodomest_switch->txrpt = LEARN_REPEATS; - } else { - eurodomest_switch->txrpt = NORMAL_REPEATS; - } -} - -static void parseCode(void) { - int binary[BINARY_LENGTH], x = 0, i = 0; - - for (x = 0; x < eurodomest_switch->rawlen - 2; x += 2) { - if ((eurodomest_switch->raw[x] >= MIN_MEDIUM_PULSE_LENGTH) && - (eurodomest_switch->raw[x] <= MAX_MEDIUM_PULSE_LENGTH) && - (eurodomest_switch->raw[x + 1] >= MIN_SHORT_PULSE_LENGTH) && - (eurodomest_switch->raw[x + 1] <= MAX_SHORT_PULSE_LENGTH)) { - binary[i++] = 0; - } else if ((eurodomest_switch->raw[x] >= MIN_SHORT_PULSE_LENGTH) && - (eurodomest_switch->raw[x] <= MAX_SHORT_PULSE_LENGTH) && - (eurodomest_switch->raw[x + 1] >= MIN_MEDIUM_PULSE_LENGTH) && - (eurodomest_switch->raw[x + 1] <= MAX_MEDIUM_PULSE_LENGTH)) { - binary[i++] = 1; - } else { - return; // decoding failed, return without creating message - } - } - - // The last 4 bits contain the unit, state and all information - - int unit = 0; - int all = 0; - int state = 0; - - if (binary[20] == 0 && binary[21] == 0 && binary[22] == 0 && binary[23] == 0) { - unit = 1; - all = 0; - state = 1; // on - } else if (binary[20] == 0 && binary[21] == 0 && binary[22] == 0 && binary[23] == 1) { - unit = 1; - all = 0; - state = 0; // off - } else if (binary[20] == 0 && binary[21] == 0 && binary[22] == 1 && binary[23] == 1) { - unit = 2; - all = 0; - state = 0; // off - } else if (binary[20] == 0 && binary[21] == 0 && binary[22] == 1 && binary[23] == 0) { - unit = 2; - all = 0; - state = 1; // on - } else if (binary[20] == 0 && binary[21] == 1 && binary[22] == 0 && binary[23] == 1) { - unit = 3; - all = 0; - state = 0; // off - } else if (binary[20] == 0 && binary[21] == 1 && binary[22] == 0 && binary[23] == 0) { - unit = 3; - all = 0; - state = 1; // on - } else if (binary[20] == 1 && binary[21] == 0 && binary[22] == 0 && binary[23] == 1) { - unit = 4; - all = 0; - state = 0; // off - } else if (binary[20] == 1 && binary[21] == 0 && binary[22] == 0 && binary[23] == 0) { - unit = 4; - all = 0; - state = 1; // on - } else if (binary[20] == 1 && binary[21] == 1 && binary[22] == 1 && binary[23] == 0) { - unit = 0; // not used, all = 1 - all = 1; - state = 0; // off - } else if (binary[20] == 1 && binary[21] == 1 && binary[22] == 0 && binary[23] == 1) { - unit = 0; // not used, all = 1 - all = 1; - state = 1; // on - } else { - return; // decoding failed, return without creating message - } - - int id = binToDec(binary, 0, 19); - createMessage(id, unit, state, all, 0); -} - -static void createLow(int s, int e) { - int i; - - for (i = s; i <= e; i += 2) { // medium - short - eurodomest_switch->raw[i] = AVG_MEDIUM_PULSE_LENGTH; - eurodomest_switch->raw[i + 1] = AVG_SHORT_PULSE_LENGTH; - } -} - -static void createHigh(int s, int e) { - int i; - - for (i = s; i <= e; i += 2) { // short - medium - eurodomest_switch->raw[i] = AVG_SHORT_PULSE_LENGTH; - eurodomest_switch->raw[i + 1] = AVG_MEDIUM_PULSE_LENGTH; - } -} - -static void createId(int id) { - int binary[255]; - int length = 0; - int i = 0, x = 0; - - length = decToBinRev(id, binary); - for (i = 0; i <= length; i++) { - if (binary[i] == 0) { - x = i * 2; - createLow(x, x+1); - } else { //so binary[i] == 1 - x = i * 2; - createHigh(x, x + 1); - } - } -} - -static int createUnitAndStateAndAll(int unit, int state, int all) { - if (unit == 1 && state == 0 && all == 0) { - createLow(40, 41); - createLow(42, 43); - createLow(44, 45); - createHigh(46, 47); - } else if (unit == 1 && state == 1 && all == 0) { - createLow(40, 41); - createLow(42, 43); - createLow(44, 45); - createLow(46, 47); - } else if (unit == 2 && state == 0 && all == 0) { - createLow(40, 41); - createLow(42, 43); - createHigh(44, 45); - createHigh(46, 47); - } else if (unit == 2 && state == 1 && all == 0) { - createLow(40, 41); - createLow(42, 43); - createHigh(44, 45); - createLow(46, 47); - } else if (unit == 3 && state == 0 && all == 0) { - createLow(40, 41); - createHigh(42, 43); - createLow(44, 45); - createHigh(46, 47); - } else if (unit == 3 && state == 1 && all == 0) { - createLow(40, 41); - createHigh(42, 43); - createLow(44, 45); - createLow(46, 47); - } else if (unit == 4 && state == 0 && all == 0) { - createHigh(40, 41); - createLow(42, 43); - createLow(44, 45); - createHigh(46, 47); - } else if (unit == 4 && state == 1 && all == 0) { - createHigh(40, 41); - createLow(42, 43); - createLow(44, 45); - createLow(46, 47); - } else if (unit == 0 && state == 0 && all == 1) { - createHigh(40, 41); - createHigh(42, 43); - createHigh(44, 45); - createLow(46, 47); - } else if (unit == 0 && state == 1 && all == 1) { - createHigh(40, 41); - createHigh(42, 43); - createLow(44, 45); - createHigh(46, 47); - } else { - logprintf(LOG_ERR, "eurodomest_switch: incorrect combination of arguments"); - return EXIT_FAILURE; - } - return EXIT_SUCCESS; -} - -static void createFooter(void) { - eurodomest_switch->raw[48] = AVG_SHORT_PULSE_LENGTH; - eurodomest_switch->raw[49] = AVG_LONG_PULSE_LENGTH; -} - -static int createCode(struct JsonNode *code) { - int id = -1; - int unit = -1; - int state = -1; - int all = 0; - int learn = -1; - double itmp = -1; - - if (json_find_number(code, "id", &itmp) == 0) - id = (int)round(itmp); - if (json_find_number(code, "unit", &itmp) == 0) - unit = (int)round(itmp); - if (json_find_number(code, "all", &itmp) == 0) - all = (int)round(itmp); - if (json_find_number(code, "off", &itmp) == 0) - state = 0; - else if (json_find_number(code, "on", &itmp) == 0) - state = 1; - if (json_find_number(code, "learn", &itmp) == 0) - learn = 1; - - if (all > 0 && learn > -1) { - logprintf(LOG_ERR, "eurodomest_switch: all and learn cannot be combined"); - return EXIT_FAILURE; - } else if (id == -1 || (unit == -1 && all == 0) || state == -1) { - logprintf(LOG_ERR, "eurodomest_switch: insufficient number of arguments"); - return EXIT_FAILURE; - } else if (id > 1048575 || id < 0) { - logprintf(LOG_ERR, "eurodomest_switch: invalid id range"); - return EXIT_FAILURE; - } else if ((unit > 4 || unit < 1) && all == 0) { - logprintf(LOG_ERR, "eurodomest_switch: invalid unit range"); - return EXIT_FAILURE; - } else { - if (unit == -1 && all == 1) { - unit = 0; - } - createMessage(id, unit, state, all, learn); - createId(id); - if (createUnitAndStateAndAll(unit, state, all) == EXIT_FAILURE) - return EXIT_FAILURE; - createFooter(); - eurodomest_switch->rawlen = RAW_LENGTH; - } - return EXIT_SUCCESS; -} - - -static void printHelp(void) { - printf("\t -t --on\t\t\tsend an on signal\n"); - printf("\t -f --off\t\t\tsend an off signal\n"); - printf("\t -u --unit=unit\t\t\tcontrol a device with this unit code\n"); - printf("\t -i --id=id\t\t\tcontrol a device with this id\n"); - printf("\t -a --all\t\t\tsend command to all devices with this id\n"); - printf("\t -l --learn\t\t\tsend multiple streams so switch can learn\n"); -} - -#if !defined(MODULE) && !defined(_WIN32) -__attribute__((weak)) -#endif -void eurodomestSwitchInit(void) { - - protocol_register(&eurodomest_switch); - protocol_set_id(eurodomest_switch, "eurodomest_switch"); - protocol_device_add(eurodomest_switch, "eurodomest_switch", "Eurodomest Switches"); - eurodomest_switch->devtype = SWITCH; - eurodomest_switch->hwtype = RF433; - eurodomest_switch->minrawlen = RAW_LENGTH; - eurodomest_switch->maxrawlen = RAW_LENGTH; - eurodomest_switch->maxgaplen = MAX_LONG_PULSE_LENGTH; - eurodomest_switch->mingaplen = MIN_LONG_PULSE_LENGTH; - - options_add(&eurodomest_switch->options, "t", "on", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); - options_add(&eurodomest_switch->options, "f", "off", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); - options_add(&eurodomest_switch->options, "u", "unit", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, "^([1-4])$"); - options_add(&eurodomest_switch->options, "i", "id", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, "^([0-9]{1}|[0-9]{2}|[0-9]{3}|[0-9]{4}|[0-9]{5}|[0-9]{6}|[0-9]{7})$"); - options_add(&eurodomest_switch->options, "a", "all", OPTION_OPT_VALUE, DEVICES_OPTIONAL, JSON_NUMBER, NULL, NULL); - options_add(&eurodomest_switch->options, "l", "learn", OPTION_NO_VALUE, DEVICES_OPTIONAL, JSON_NUMBER, NULL, NULL); - - options_add(&eurodomest_switch->options, "0", "readonly", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)0, "^[10]$"); - options_add(&eurodomest_switch->options, "0", "confirm", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)0, "^[10]$"); - - eurodomest_switch->parseCode = &parseCode; - eurodomest_switch->createCode = &createCode; - eurodomest_switch->printHelp = &printHelp; - eurodomest_switch->validate = &validate; -} - -#if defined(MODULE) && !defined(_WIN32) -void compatibility(struct module_t *module) { - module->name = "eurodomest_switch"; - module->version = "1.0"; - module->reqversion = "6.0"; - module->reqcommit = "84"; -} - -void init(void) { - eurodomestSwitchInit(); -} -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/eurodomest_switch.h b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/eurodomest_switch.h deleted file mode 100644 index 9af32432..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/eurodomest_switch.h +++ /dev/null @@ -1,27 +0,0 @@ -/* - Copyright (C) 2015 woutput - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#ifndef _PROTOCOL_EURODOMEST_SWITCH_H_ -#define _PROTOCOL_EURODOMEST_SWITCH_H_ - -#include "../protocol.h" - -struct protocol_t *eurodomest_switch; -void eurodomestSwitchInit(void); - -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/ev1527.c b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/ev1527.c deleted file mode 100644 index c5abbd61..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/ev1527.c +++ /dev/null @@ -1,115 +0,0 @@ -/* - Copyright (C) 2015 CurlyMo and Meloen - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#include -#include -#include -#include - -#include "../../core/pilight.h" -#include "../../core/common.h" -#include "../../core/dso.h" -#include "../../core/log.h" -#include "../protocol.h" -#include "../../core/binary.h" -#include "../../core/gc.h" -#include "ev1527.h" - -#define PULSE_MULTIPLIER 5 -#define MIN_PULSE_LENGTH 251 -#define MAX_PULSE_LENGTH 311 -#define AVG_PULSE_LENGTH 256 -#define RAW_LENGTH 50 - -static int validate(void) { - if(ev1527->rawlen == RAW_LENGTH) { - if(ev1527->raw[ev1527->rawlen-1] >= (MIN_PULSE_LENGTH*PULSE_DIV) && - ev1527->raw[ev1527->rawlen-1] <= (MAX_PULSE_LENGTH*PULSE_DIV)) { - return 0; - } - } - - return -1; -} - -static void createMessage(int unitcode, int state) { - ev1527->message = json_mkobject(); - json_append_member(ev1527->message, "unitcode", json_mknumber(unitcode, 0)); - if(state == 0) { - json_append_member(ev1527->message, "state", json_mkstring("opened")); - } else { - json_append_member(ev1527->message, "state", json_mkstring("closed")); - } -} - -static void parseCode(void) { - int binary[RAW_LENGTH/2], x = 0, i = 0; - - if(ev1527->rawlen>RAW_LENGTH) { - logprintf(LOG_ERR, "ev1527: parsecode - invalid parameter passed %d", ev1527->rawlen); - return; - } - - for(x=0;xrawlen-2;x+=2) { - if(ev1527->raw[x+3] > (int)((double)AVG_PULSE_LENGTH*((double)PULSE_MULTIPLIER/2))) { - binary[i++] = 1; - } else { - binary[i++] = 0; - } - } - - int unitcode = binToDec(binary, 0, 19); - int state = binary[20]; - createMessage(unitcode, state); -} - -#if !defined(MODULE) && !defined(_WIN32) -__attribute__((weak)) -#endif -void ev1527Init(void) { - - protocol_register(&ev1527); - protocol_set_id(ev1527, "ev1527"); - protocol_device_add(ev1527, "ev1527", "ev1527 contact sensor"); - ev1527->devtype = CONTACT; - ev1527->hwtype = RF433; - ev1527->minrawlen = RAW_LENGTH; - ev1527->maxrawlen = RAW_LENGTH; - ev1527->maxgaplen = MAX_PULSE_LENGTH*PULSE_DIV; - ev1527->mingaplen = MIN_PULSE_LENGTH*PULSE_DIV; - - options_add(&ev1527->options, "u", "unitcode", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, "^(104857[0-5]|10485[0-6][0-9]|1048[0-4][0-9][0-9]|104[0-7][0-9]{3}|10[0-3][0-9]{4}|0?[0-9]{1,6})$"); - options_add(&ev1527->options, "t", "opened", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); - options_add(&ev1527->options, "f", "closed", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); - - ev1527->parseCode=&parseCode; - ev1527->validate=&validate; -} - -#if defined(MODULE) && !defined(_WIN32) -void compatibility(struct module_t *module) { - module->name = "ev1527"; - module->version = "1.2"; - module->reqversion = "6.0"; - module->reqcommit = "84"; -} - -void init(void) { - ev1527Init(); -} -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/ev1527.h b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/ev1527.h deleted file mode 100644 index ec405732..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/ev1527.h +++ /dev/null @@ -1,27 +0,0 @@ -/* - Copyright (C) 2014 CurlyMo - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#ifndef _PROTOCOL_EV1527_H_ -#define _PROTOCOL_EV1527_H_ - -#include "../protocol.h" - -struct protocol_t *ev1527; -void ev1527Init(void); - -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/heitech.c b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/heitech.c deleted file mode 100644 index 98820cfc..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/heitech.c +++ /dev/null @@ -1,238 +0,0 @@ -/* - - Copyright (C) 2015 CurlyMo & Meloen - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#include -#include -#include -#include - -#include "../../core/pilight.h" -#include "../../core/common.h" -#include "../../core/dso.h" -#include "../../core/log.h" -#include "../../core/binary.h" -#include "../../core/gc.h" -#include "../protocol.h" -#include "heitech.h" - -#define PULSE_MULTIPLIER 3 -#define MIN_PULSE_LENGTH 270 -#define MAX_PULSE_LENGTH 290 -#define AVG_PULSE_LENGTH 280 -#define RAW_LENGTH 50 - -static int validate(void) { - if(heitech->rawlen == RAW_LENGTH) { - if(heitech->raw[heitech->rawlen-1] >= (MIN_PULSE_LENGTH*PULSE_DIV) && - heitech->raw[heitech->rawlen-1] <= (MAX_PULSE_LENGTH*PULSE_DIV)) { - return 0; - } - } - - return -1; -} - -static void createMessage(int systemcode, int unitcode, int state) { - heitech->message = json_mkobject(); - json_append_member(heitech->message, "systemcode", json_mknumber(systemcode, 0)); - json_append_member(heitech->message, "unitcode", json_mknumber(unitcode, 0)); - - if(state == 0) { - json_append_member(heitech->message, "state", json_mkstring("on")); - } else { - json_append_member(heitech->message, "state", json_mkstring("off")); - } -} - -static void parseCode(void) { - int x = 0, binary[RAW_LENGTH/4]; - - if(heitech->rawlen>RAW_LENGTH) { - logprintf(LOG_ERR, "heitech: parsecode - invalid parameter passed %d", heitech->rawlen); - return; - } - - for(x=0;xrawlen-2;x+=4) { - if(heitech->raw[x+3] > (int)((double)AVG_PULSE_LENGTH*((double)PULSE_MULTIPLIER/2))) { - binary[x/4]=1; - } else { - binary[x/4]=0; - } - } - - int systemcode = binToDec(binary, 0, 4); - int unitcode = binToDec(binary, 5, 9); - int check = binary[10]; - int state = binary[11]; - - if(check != state) { - createMessage(systemcode, unitcode, state); - } -} - -static void createLow(int s, int e) { - int i; - - for(i=s;i<=e;i+=4) { - heitech->raw[i]=AVG_PULSE_LENGTH; - heitech->raw[i+1]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - heitech->raw[i+2]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - heitech->raw[i+3]=AVG_PULSE_LENGTH; - } -} - -static void createHigh(int s, int e) { - int i; - - for(i=s;i<=e;i+=4) { - heitech->raw[i]=AVG_PULSE_LENGTH; - heitech->raw[i+1]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - heitech->raw[i+2]=AVG_PULSE_LENGTH; - heitech->raw[i+3]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - } -} - -static void clearCode(void) { - createLow(0,47); -} - -static void createSystemCode(int systemcode) { - int binary[255]; - int length = 0; - int i=0, x=0; - - length = decToBinRev(systemcode, binary); - for(i=0;i<=length;i++) { - if(binary[i]==1) { - x=i*4; - createHigh(x, x+3); - } - } -} - -static void createUnitCode(int unitcode) { - int binary[255]; - int length = 0; - int i=0, x=0; - - length = decToBinRev(unitcode, binary); - for(i=0;i<=length;i++) { - if(binary[i]==1) { - x=i*4; - createHigh(20+x, 20+x+3); - } - } -} - -static void createState(int state) { - if(state == 1) { - createHigh(44, 47); - } else { - createHigh(40, 43); - } -} - -static void createFooter(void) { - heitech->raw[48]=(AVG_PULSE_LENGTH); - heitech->raw[49]=(PULSE_DIV*AVG_PULSE_LENGTH); -} -static int createCode(JsonNode *code) { - int systemcode = -1; - int unitcode = -1; - int state = -1; - double itmp = 0; - - if(json_find_number(code, "systemcode", &itmp) == 0) - systemcode = (int)round(itmp); - if(json_find_number(code, "unitcode", &itmp) == 0) - unitcode = (int)round(itmp); - if(json_find_number(code, "off", &itmp) == 0) - state=1; - else if(json_find_number(code, "on", &itmp) == 0) - state=0; - - if(systemcode == -1 || unitcode == -1 || state == -1) { - logprintf(LOG_ERR, "heitech: insufficient number of arguments"); - return EXIT_FAILURE; - } else if(systemcode > 31 || systemcode < 0) { - logprintf(LOG_ERR, "heitech: invalid systemcode range"); - return EXIT_FAILURE; - } else if(unitcode > 31 || unitcode < 0) { - logprintf(LOG_ERR, "heitech: invalid unitcode range"); - return EXIT_FAILURE; - } else { - createMessage(systemcode, unitcode, state); - clearCode(); - createSystemCode(systemcode); - createUnitCode(unitcode); - createState(state); - createFooter(); - heitech->rawlen = RAW_LENGTH; - } - return EXIT_SUCCESS; -} - -static void printHelp(void) { - printf("\t -s --systemcode=systemcode\tcontrol a device with this systemcode\n"); - printf("\t -u --unitcode=unitcode\t\tcontrol a device with this unitcode\n"); - printf("\t -t --on\t\t\tsend an on signal\n"); - printf("\t -f --off\t\t\tsend an off signal\n"); -} - -#if !defined(MODULE) && !defined(_WIN32) -__attribute__((weak)) -#endif -void heitechInit(void) { - - protocol_register(&heitech); - protocol_set_id(heitech, "heitech"); - protocol_device_add(heitech, "heitech", "Heitech series Switches"); - heitech->devtype = SWITCH; - heitech->hwtype = RF433; - heitech->minrawlen = RAW_LENGTH; - heitech->maxrawlen = RAW_LENGTH; - heitech->maxgaplen = MAX_PULSE_LENGTH*PULSE_DIV; - heitech->mingaplen = MIN_PULSE_LENGTH*PULSE_DIV; - - options_add(&heitech->options, "s", "systemcode", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, "^(3[012]?|[012][0-9]|[0-9]{1})$"); - options_add(&heitech->options, "u", "unitcode", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, "^(3[012]?|[012][0-9]|[0-9]{1})$"); - options_add(&heitech->options, "t", "on", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); - options_add(&heitech->options, "f", "off", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); - - options_add(&heitech->options, "0", "readonly", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)0, "^[10]{1}$"); - - heitech->parseCode=&parseCode; - heitech->createCode=&createCode; - heitech->printHelp=&printHelp; - heitech->validate=&validate; -} - -#if defined(MODULE) && !defined(_WIN32) -void compatibility(struct module_t *module) { - module->name = "heitech"; - module->version = "1.1"; - module->reqversion = "6.0"; - module->reqcommit = "187"; -} - -void init(void) { - heitechInit(); -} - -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/heitech.h b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/heitech.h deleted file mode 100644 index f04eae0d..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/heitech.h +++ /dev/null @@ -1,27 +0,0 @@ -/* - Copyright (C) 2015 CurlyMo & meloen - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#ifndef _PROTOCOL_HEITECH_H_ -#define _PROTOCOL_HEITECH_H_ - -#include "../protocol.h" - -struct protocol_t *heitech; -void heitechInit(void); - -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/impuls.c b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/impuls.c deleted file mode 100644 index e4dbeeda..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/impuls.c +++ /dev/null @@ -1,250 +0,0 @@ -/* - Copyright (C) 2013 Bram1337 & CurlyMo - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#include -#include -#include -#include - -#include "../../core/pilight.h" -#include "../../core/common.h" -#include "../../core/dso.h" -#include "../../core/log.h" -#include "../protocol.h" -#include "../../core/binary.h" -#include "../../core/gc.h" -#include "impuls.h" - -#define PULSE_MULTIPLIER 3 -#define MIN_PULSE_LENGTH 130 -#define MAX_PULSE_LENGTH 170 -#define AVG_PULSE_LENGTH 150 -#define RAW_LENGTH 50 - -static int validate(void) { - if(impuls->rawlen == RAW_LENGTH) { - if(impuls->raw[impuls->rawlen-1] >= (MIN_PULSE_LENGTH*PULSE_DIV) && - impuls->raw[impuls->rawlen-1] <= (MAX_PULSE_LENGTH*PULSE_DIV)) { - return 0; - } - } - - return -1; -} - -static void createMessage(int systemcode, int programcode, int state) { - impuls->message = json_mkobject(); - json_append_member(impuls->message, "systemcode", json_mknumber(systemcode, 0)); - json_append_member(impuls->message, "programcode", json_mknumber(programcode, 0)); - if(state == 1) { - json_append_member(impuls->message, "state", json_mkstring("on")); - } else { - json_append_member(impuls->message, "state", json_mkstring("off")); - } -} - -static void parseCode(void) { - int x = 0, binary[RAW_LENGTH/4]; - - if(impuls->rawlen>RAW_LENGTH) { - logprintf(LOG_ERR, "impuls: parsecode - invalid parameter passed %d", impuls->rawlen); - return; - } - - /* Convert the one's and zero's into binary */ - for(x=0;xrawlen-2;x+=4) { - if(impuls->raw[x+3] > (int)((double)AVG_PULSE_LENGTH*((double)PULSE_MULTIPLIER/2)) || - impuls->raw[x+0] > (int)((double)AVG_PULSE_LENGTH*((double)PULSE_MULTIPLIER/2))) { - binary[x/4]=1; - } else { - binary[x/4]=0; - } - } - - int systemcode = binToDec(binary, 0, 4); - int programcode = binToDec(binary, 5, 9); - int check = binary[10]; - int state = binary[11]; - - if(check != state) { - createMessage(systemcode, programcode, state); - } -} - -static void createLow(int s, int e) { - int i; - - for(i=s;i<=e;i+=4) { - impuls->raw[i]=AVG_PULSE_LENGTH; - impuls->raw[i+1]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - impuls->raw[i+2]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - impuls->raw[i+3]=AVG_PULSE_LENGTH; - } -} - -static void createMed(int s, int e) { - int i; - - for(i=s;i<=e;i+=4) { - impuls->raw[i]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - impuls->raw[i+1]=AVG_PULSE_LENGTH; - impuls->raw[i+2]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - impuls->raw[i+3]=AVG_PULSE_LENGTH; - } -} - -static void createHigh(int s, int e) { - int i; - - for(i=s;i<=e;i+=4) { - impuls->raw[i]=AVG_PULSE_LENGTH; - impuls->raw[i+1]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - impuls->raw[i+2]=AVG_PULSE_LENGTH; - impuls->raw[i+3]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - } -} - -static void clearCode(void) { - createLow(0,47); -} - -static void createSystemCode(int systemcode) { - int binary[255]; - int length = 0; - int i=0, x=0; - - length = decToBinRev(systemcode, binary); - for(i=0;i<=length;i++) { - if(binary[i]==1) { - x=i*4; - createMed(x, x+3); - } - } -} - -static void createProgramCode(int programcode) { - int binary[255]; - int length = 0; - int i=0, x=0; - - length = decToBinRev(programcode, binary); - for(i=0;i<=length;i++) { - if(binary[i]==1) { - x=i*4; - createHigh(20+x, 20+x+3); - } - } -} - -static void createState(int state) { - if(state == 0) { - createHigh(40, 43); - } else { - createHigh(44, 47); - } -} - -static void createFooter(void) { - impuls->raw[48]=(AVG_PULSE_LENGTH); - impuls->raw[49]=(PULSE_DIV*AVG_PULSE_LENGTH); -} - -static int createCode(struct JsonNode *code) { - int systemcode = -1; - int programcode = -1; - int state = -1; - double itmp = 0; - - if(json_find_number(code, "systemcode", &itmp) == 0) - systemcode = (int)round(itmp); - if(json_find_number(code, "programcode", &itmp) == 0) - programcode = (int)round(itmp); - if(json_find_number(code, "off", &itmp) == 0) - state=0; - else if(json_find_number(code, "on", &itmp) == 0) - state=1; - - if(systemcode == -1 || programcode == -1 || state == -1) { - logprintf(LOG_ERR, "impuls: insufficient number of arguments"); - return EXIT_FAILURE; - } else if(systemcode > 31 || systemcode < 0) { - logprintf(LOG_ERR, "impuls: invalid systemcode range"); - return EXIT_FAILURE; - } else if(programcode > 31 || programcode < 0) { - logprintf(LOG_ERR, "impuls: invalid programcode range"); - return EXIT_FAILURE; - } else { - createMessage(systemcode, programcode, state); - clearCode(); - createSystemCode(systemcode); - createProgramCode(programcode); - createState(state); - createFooter(); - impuls->rawlen = RAW_LENGTH; - } - return EXIT_SUCCESS; -} - -static void printHelp(void) { - printf("\t -s --systemcode=systemcode\tcontrol a device with this systemcode\n"); - printf("\t -u --programcode=programcode\tcontrol a device with this programcode\n"); - printf("\t -t --on\t\t\tsend an on signal\n"); - printf("\t -f --off\t\t\tsend an off signal\n"); -} - -#if !defined(MODULE) && !defined(_WIN32) -__attribute__((weak)) -#endif -void impulsInit(void) { - - protocol_register(&impuls); - protocol_set_id(impuls, "impuls"); - protocol_device_add(impuls, "impuls", "Impuls Switches"); - impuls->devtype = SWITCH; - impuls->hwtype = RF433; - impuls->minrawlen = RAW_LENGTH; - impuls->maxrawlen = RAW_LENGTH; - impuls->maxgaplen = MAX_PULSE_LENGTH*PULSE_DIV; - impuls->mingaplen = MIN_PULSE_LENGTH*PULSE_DIV; - - options_add(&impuls->options, "s", "systemcode", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, "^(3[012]?|[012][0-9]|[0-9]{1})$"); - options_add(&impuls->options, "u", "programcode", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, "^(3[012]?|[012][0-9]|[0-9]{1})$"); - options_add(&impuls->options, "t", "on", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); - options_add(&impuls->options, "f", "off", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); - - options_add(&impuls->options, "0", "readonly", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)0, "^[10]{1}$"); - options_add(&impuls->options, "0", "confirm", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)0, "^[10]{1}$"); - - impuls->parseCode=&parseCode; - impuls->createCode=&createCode; - impuls->printHelp=&printHelp; - impuls->validate=&validate; -} - -#if defined(MODULE) && !defined(_WIN32) -void compatibility(struct module_t *module) { - module->name = "impuls"; - module->version = "2.4"; - module->reqversion = "6.0"; - module->reqcommit = "84"; -} - -void init(void) { - impulsInit(); -} -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/impuls.h b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/impuls.h deleted file mode 100644 index bc8aa25d..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/impuls.h +++ /dev/null @@ -1,27 +0,0 @@ -/* - Copyright (C) 2013 Bram1337 & CurlyMo - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#ifndef _PROTOCOL_IMPULS_H_ -#define _PROTOCOL_IMPULS_H_ - -#include "../protocol.h" - -struct protocol_t *impuls; -void impulsInit(void); - -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/kerui_d026.c b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/kerui_d026.c deleted file mode 100644 index d7448793..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/kerui_d026.c +++ /dev/null @@ -1,117 +0,0 @@ -/* - Copyright (C) 2017 - 2019 by CurlyMo, Meloen, zeltom, mwka - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. -*/ - -#include -#include -#include -#include - -#include "../../core/pilight.h" -#include "../../core/common.h" -#include "../../core/dso.h" -#include "../../core/log.h" -#include "../protocol.h" -#include "../../core/binary.h" -#include "../../core/gc.h" -#include "kerui_d026.h" - - -#define PULSE_MULTIPLIER 3 -#define MIN_PULSE_LENGTH 260 -#define MAX_PULSE_LENGTH 310 -#define AVG_PULSE_LENGTH 280 -#define RAW_LENGTH 50 - -static int validate(void) { - if(kerui_D026->rawlen == RAW_LENGTH) { - if(kerui_D026->raw[kerui_D026->rawlen-1] >= (MIN_PULSE_LENGTH*PULSE_DIV) && - kerui_D026->raw[kerui_D026->rawlen-1] <= (MAX_PULSE_LENGTH*PULSE_DIV)) { - return 0; - } - } - - return -1; -} - -static void createMessage(int unitcode, int state, int state2, int state3, int state4) { - kerui_D026->message = json_mkobject(); - json_append_member(kerui_D026->message, "unitcode", json_mknumber(unitcode, 0)); - - if(state4 == 0) { - json_append_member(kerui_D026->message, "state", json_mkstring("opened")); - } - else if(state == 0) { - json_append_member(kerui_D026->message, "state", json_mkstring("closed")); - } - else if(state2 == 0) { - json_append_member(kerui_D026->message, "state", json_mkstring("tamper")); - } - else if(state3 == 0) { - json_append_member(kerui_D026->message, "state", json_mkstring("not used")); - } - else{ - json_append_member(kerui_D026->message, "battery", json_mkstring("low")); - } - -} - -static void parseCode(void) { - int binary[RAW_LENGTH/2], x = 0, i = 0; - - for(x=0;xrawlen-2;x+=2) { - if(kerui_D026->raw[x] > (int)((double)AVG_PULSE_LENGTH*((double)PULSE_MULTIPLIER/2))) { - binary[i++] = 1; - } else { - binary[i++] = 0; - } - } - - int unitcode = binToDec(binary, 0, 19); - int state = binary[20]; - int state2 = binary[21]; - int state3 = binary[22]; - int state4 = binary[23]; - createMessage(unitcode, state, state2, state3, state4); -} - -#if !defined(MODULE) && !defined(_WIN32) -__attribute__((weak)) -#endif -void keruiD026Init(void) { - - protocol_register(&kerui_D026); - protocol_set_id(kerui_D026, "kerui_D026"); - protocol_device_add(kerui_D026, "kerui_D026", "KERUI D026 Door sensor"); - kerui_D026->devtype = CONTACT; - kerui_D026->hwtype = RF433; - kerui_D026->minrawlen = RAW_LENGTH; - kerui_D026->maxrawlen = RAW_LENGTH; - kerui_D026->maxgaplen = MAX_PULSE_LENGTH*PULSE_DIV; - kerui_D026->mingaplen = MIN_PULSE_LENGTH*PULSE_DIV; - - options_add(&kerui_D026->options, "u", "unitcode", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, NULL); - options_add(&kerui_D026->options, "t", "opened", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); - options_add(&kerui_D026->options, "f", "closed", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); - options_add(&kerui_D026->options, "a", "tamper", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); - - kerui_D026->parseCode=&parseCode; - kerui_D026->validate=&validate; -} - -#if defined(MODULE) && !defined(_WIN32) -void compatibility(struct module_t *module) { - module->name = "kerui_D026"; - module->version = "2.0"; - module->reqversion = "6.0"; - module->reqcommit = "84"; -} - -void init(void) { - keruiD026Init(); -} -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/kerui_d026.h b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/kerui_d026.h deleted file mode 100644 index 2a2baa36..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/kerui_d026.h +++ /dev/null @@ -1,17 +0,0 @@ -/* - Copyright (C) 2017 - 2019 by CurlyMo, Meloen, zeltom, mwka - - This Source Code Form is subject to the terms of the Mozilla Public - License, v. 2.0. If a copy of the MPL was not distributed with this - file, You can obtain one at http://mozilla.org/MPL/2.0/. -*/ - -#ifndef _PROTOCOL_KERUI_D026_H_ -#define _PROTOCOL_KERUI_D026_H_ - -#include "../protocol.h" - -struct protocol_t *kerui_D026; -void keruiD026Init(void); - -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/livolo_switch.c b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/livolo_switch.c deleted file mode 100644 index a7a72087..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/livolo_switch.c +++ /dev/null @@ -1,207 +0,0 @@ -/* - Copyright (C) 2017 Oleksii Serdiuk - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#include "livolo_switch.h" - -#include "../../core/binary.h" -#include "../../core/log.h" - -#if defined(MODULE) && !defined(_WIN32) -# include "../../core/dso.h" -#endif - -#include -#include -#include - -// Based on the protocol description from -// http://platenspeler.github.io/DeveloperGuide/433Transmitters/433messaging.html -// with timing adjustments, based on sniffing the remote I own - -#define REPEATS 120 -#define PULSE_LENGTH 170 -#define MIN_RAW_LENGTH 24 -#define MAX_RAW_LENGTH 47 - -#define ID_BITS 16 -#define UNIT_BITS 7 - -static int createHeader() { - livolo_switch->raw[0] = PULSE_LENGTH*3.5; - return 1; -} - -static int createLow(int i) { - livolo_switch->raw[i] = PULSE_LENGTH; - livolo_switch->raw[i+1] = PULSE_LENGTH; - return 2; -} - -static int createHigh(int i) { - livolo_switch->raw[i] = PULSE_LENGTH*2; - return 1; -} - -static int createBits(int value, int start, int length) { - int binary[255]; - int l = 0; - int i = 0, x = start; - - l = decToBin(value, binary); - // Pad with zeroes - for(i=0;imessage = json_mkobject(); - - json_append_member(livolo_switch->message, "id", json_mknumber(id, 0)); - - if(off == 1) { - json_append_member(livolo_switch->message, "off", json_mknumber(off, 0)); - } else { - json_append_member(livolo_switch->message, "key", json_mknumber(key, 0)); - } -} - -static int createCode(JsonNode *code) { - int id = -1; - int key = -1; - int off = 0; - int x = 0; - double itmp = -1; - - if(json_find_number(code, "id", &itmp) == 0) - id = (int)round(itmp); - if(json_find_number(code, "key", &itmp) == 0) - key = (int)round(itmp); - if(json_find_number(code, "off", &itmp) == 0) { - off = 1; - key = 0; - } - - if(off > 0 && key > 0) { - logprintf(LOG_ERR, "livolo_switch: off and key cannot be combined"); - return EXIT_FAILURE; - } else if(id == -1 || (key == -1 && off == 0)) { - logprintf(LOG_ERR, "livolo_switch: insufficient number of arguments"); - return EXIT_FAILURE; - } else if(id < 0 || id > 65535) { - logprintf(LOG_ERR, "livolo_switch: invalid id range"); - return EXIT_FAILURE; - } else if((key < 1 || key > 10) && off == 0) { - logprintf(LOG_ERR, "livolo_switch: invalid key range"); - return EXIT_FAILURE; - } else { - createMessage(id, key, off); - - x = createHeader(); - x = createBits(id, x, ID_BITS); - x = createBits(createKeycode(key), x, UNIT_BITS); - livolo_switch->rawlen = x; - } - - return EXIT_SUCCESS; -} - -static void printHelp(void) { - printf("\t -i --id=id\t\t\tsend with id of the remote (0..65535)\n"); - printf("\t -n --key=number\t\t\tsend with key number on the remote (1..10)\n"); - printf("\t -f --off\t\t\tsend turn off code for the remote\n"); -} - -#if !defined(MODULE) && !defined(_WIN32) -__attribute__((weak)) -#endif -void livoloSwitchInit(void) { - protocol_register(&livolo_switch); - protocol_set_id(livolo_switch, "livolo_switch"); - protocol_device_add(livolo_switch, "livolo_switch", "Livolo Switches"); - livolo_switch->devtype = SWITCH; - livolo_switch->hwtype = RF433; - livolo_switch->txrpt = REPEATS; - livolo_switch->minrawlen = MIN_RAW_LENGTH; - livolo_switch->maxrawlen = MAX_RAW_LENGTH; - - options_add(&livolo_switch->options, 'i', "id", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, - // 16 bits: 0..65535 - "^([0-5]?[0-9]{1,4}|(6[0-4][0-9]{3})|(65[0-4][0-9]{2})|(655[0-2][0-9])|(6553[0-5]))$"); - options_add(&livolo_switch->options, 'n', "key", OPTION_OPT_VALUE, DEVICES_ID, JSON_NUMBER, NULL, - // 7 its: 0..127 - "^(([0-9]{1,2})|(1[0-1][0-9])|(12[0-7]))$"); - options_add(&livolo_switch->options, 'f', "off", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); - - options_add(&livolo_switch->options, 0, "readonly", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, NULL, "^[01]$"); - options_add(&livolo_switch->options, 0, "confirm", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, NULL, "^[01]$"); - - livolo_switch->createCode=&createCode; - livolo_switch->printHelp=&printHelp; -} - -#if defined(MODULE) && !defined(_WIN32) -void compatibility(struct module_t *module) { - module->name = "livolo_switch"; - module->version = "0.1"; - module->reqversion = "7.0"; - module->reqcommit = NULL; -} - -void init(void) { - livoloSwitchInit(); -} -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/livolo_switch.h b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/livolo_switch.h deleted file mode 100644 index f379df25..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/livolo_switch.h +++ /dev/null @@ -1,27 +0,0 @@ -/* - Copyright (C) 2017 Oleksii Serdiuk - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#ifndef _PROTOCOL_LIVOLO_SWITCH_H_ -#define _PROTOCOL_LIVOLO_SWITCH_H_ - -#include "../protocol.h" - -struct protocol_t *livolo_switch; -void livoloSwitchInit(void); - -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/logilink_switch.c b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/logilink_switch.c deleted file mode 100644 index f84d51b0..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/logilink_switch.c +++ /dev/null @@ -1,243 +0,0 @@ -/* - Copyright (C) 2015 CurlyMo, Meloen and Scarala - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#include -#include -#include -#include - -#include "../../core/pilight.h" -#include "../../core/common.h" -#include "../../core/dso.h" -#include "../../core/log.h" -#include "../protocol.h" -#include "../../core/binary.h" -#include "../../core/gc.h" -#include "logilink_switch.h" - -#define PULSE_MULTIPLIER 3 -#define MIN_PULSE_LENGTH 279 -#define MAX_PULSE_LENGTH 289 -#define AVG_PULSE_LENGTH 284 -#define RAW_LENGTH 50 - -static int validate(void) { - if(logilink_switch->rawlen == RAW_LENGTH) { - if(logilink_switch->raw[logilink_switch->rawlen-1] >= (MIN_PULSE_LENGTH*PULSE_DIV) && - logilink_switch->raw[logilink_switch->rawlen-1] <= (MAX_PULSE_LENGTH*PULSE_DIV)) { - return 0; - } - } - - return -1; -} - -static void createMessage(int systemcode, int unitcode, int state) { - logilink_switch->message = json_mkobject(); - json_append_member(logilink_switch->message, "systemcode", json_mknumber(systemcode, 0)); - json_append_member(logilink_switch->message, "unitcode", json_mknumber(unitcode, 0)); - if(state == 0) { - json_append_member(logilink_switch->message, "state", json_mkstring("on")); - } else { - json_append_member(logilink_switch->message, "state", json_mkstring("off")); - } -} - -static void parseCode(void) { - int i = 0, x = 0, binary[RAW_LENGTH/2]; - int systemcode = 0, state = 0, unitcode = 0; - - if(logilink_switch->rawlen>RAW_LENGTH) { - logprintf(LOG_ERR, "logilink_switch: parsecode - invalid parameter passed %d", logilink_switch->rawlen); - return; - } - - for(x=0;xrawlen-1;x+=2) { - if(logilink_switch->raw[x] > (int)((double)AVG_PULSE_LENGTH*((double)PULSE_MULTIPLIER/2))) { - binary[i++] = 1; - } else { - binary[i++] = 0; - } - } - systemcode = binToDecRev(binary, 0, 19); - state = binary[20]; - unitcode = binToDecRev(binary, 21, 23); - - createMessage(systemcode, unitcode, state); -} - -static void createLow(int s, int e) { - int i = 0; - - for(i=s;i<=e;i+=2) { - logilink_switch->raw[i]=(AVG_PULSE_LENGTH); - logilink_switch->raw[i+1]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - } -} - -static void createHigh(int s, int e) { - int i = 0; - - for(i=s;i<=e;i+=2) { - logilink_switch->raw[i]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - logilink_switch->raw[i+1]=(AVG_PULSE_LENGTH); - } -} - -static void clearCode(void) { - createLow(0, logilink_switch->rawlen-2); -} - -static void createSystemCode(int systemcode) { - int binary[255]; - int length=0; - int i = 0, x = 38; - - length = decToBin(systemcode, binary); - for(i=length;i>=0;i--) { - if(binary[i] == 1) { - createHigh(x, x+1); - } - - x -= 2; - } -} - -static void createUnitCode(int unitcode) { - switch(unitcode) { - case 7: - createHigh(42, 47); // Button 1 - break; - case 3: - createLow(42, 43); // Button 2 - createHigh(44, 47); - break; - case 5: - createHigh(42, 43); // Button 3 - createLow(44, 45); - createHigh(46, 47); - break; - case 6: - createHigh(42, 45); // Button 4 - createLow(46, 47); - break; - case 0: - createLow(42, 47); // Button ALL OFF - break; - default: - break; - } -} - -static void createState(int state) { - if(state == 1) { - createLow(40, 41); - } else { - createHigh(40, 41); - } -} - -static void createFooter(void) { - logilink_switch->raw[48]=(AVG_PULSE_LENGTH); - logilink_switch->raw[49]=(PULSE_DIV*AVG_PULSE_LENGTH); -} - -static int createCode(struct JsonNode *code) { - int systemcode = -1; - int unitcode = -1; - int state = -1; - double itmp = 0; - - if(json_find_number(code, "systemcode", &itmp) == 0) - systemcode = (int)round(itmp); - if(json_find_number(code, "unitcode", &itmp) == 0) - unitcode = (int)round(itmp); - if(json_find_number(code, "off", &itmp) == 0) - state=1; - else if(json_find_number(code, "on", &itmp) == 0) - state=0; - - if(systemcode == -1 || unitcode == -1 || state == -1) { - logprintf(LOG_ERR, "logilink_switch: insufficient number of arguments"); - return EXIT_FAILURE; - } else if(systemcode > 2097151 || systemcode < 0) { - logprintf(LOG_ERR, "logilink_switch: invalid systemcode range"); - return EXIT_FAILURE; - } else if(unitcode > 7 || unitcode < 0) { - logprintf(LOG_ERR, "logilink_switch: invalid unitcode range"); - return EXIT_FAILURE; - } else { - createMessage(systemcode, unitcode, state); - clearCode(); - createSystemCode(systemcode); - createUnitCode(unitcode); - createState(state); - createFooter(); - logilink_switch->rawlen = RAW_LENGTH; - } - return EXIT_SUCCESS; -} - -static void printHelp(void) { - printf("\t -s --systemcode=systemcode\tcontrol a device with this systemcode\n"); - printf("\t -u --unitcode=unitcode\t\tcontrol a device with this unitcode\n"); - printf("\t -t --on\t\t\tsend an on signal\n"); - printf("\t -f --off\t\t\tsend an off signal\n"); -} - -#if !defined(MODULE) && !defined(_WIN32) -__attribute__((weak)) -#endif - -void logilinkSwitchInit(void) { - protocol_register(&logilink_switch); - protocol_set_id(logilink_switch, "logilink_switch"); - protocol_device_add(logilink_switch, "logilink_switch", "Logilink Switches"); - logilink_switch->devtype = SWITCH; - logilink_switch->hwtype = RF433; - logilink_switch->minrawlen = RAW_LENGTH; - logilink_switch->maxrawlen = RAW_LENGTH; - logilink_switch->maxgaplen = MAX_PULSE_LENGTH*PULSE_DIV; - logilink_switch->mingaplen = MIN_PULSE_LENGTH*PULSE_DIV; - - options_add(&logilink_switch->options, "s", "systemcode", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, NULL); - options_add(&logilink_switch->options, "u", "unitcode", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, "^[0-7]$"); - options_add(&logilink_switch->options, "t", "on", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); - options_add(&logilink_switch->options, "f", "off", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); - - options_add(&logilink_switch->options, "0", "readonly", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)0, "^[10]{1}$"); - options_add(&logilink_switch->options, "0", "confirm", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)0, "^[10]{1}$"); - - logilink_switch->parseCode=&parseCode; - logilink_switch->createCode=&createCode; - logilink_switch->printHelp=&printHelp; - logilink_switch->validate=&validate; -} - -#if defined(MODULE) && !defined(_WIN32) -void compatibility(struct module_t *module) { - module->name = "logilink_sitch"; - module->version = "1.1"; - module->reqversion = "6.0"; - module->reqcommit = "84"; -} - -void init(void) { - logilinkSwitchInit(); -} -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/logilink_switch.h b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/logilink_switch.h deleted file mode 100644 index 373fef40..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/logilink_switch.h +++ /dev/null @@ -1,27 +0,0 @@ -/* - Copyright (C) 2015 CurlyMo, Meloen and Scarala - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#ifndef _PROTOCOL_LOGILINK_SWITCH_H_ -#define _PROTOCOL_LOGILINK_SWITCH_H_ - -#include "../protocol.h" - -struct protocol_t *logilink_switch; -void logilinkSwitchInit(void); - -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/mumbi.c b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/mumbi.c deleted file mode 100644 index ea254194..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/mumbi.c +++ /dev/null @@ -1,234 +0,0 @@ -/* - Copyright (C) 2014 CurlyMo - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#include -#include -#include -#include - -#include "../../core/pilight.h" -#include "../../core/common.h" -#include "../../core/dso.h" -#include "../../core/log.h" -#include "../protocol.h" -#include "../../core/binary.h" -#include "../../core/gc.h" -#include "mumbi.h" - -#define PULSE_MULTIPLIER 3 -#define MIN_PULSE_LENGTH 307 -#define MAX_PULSE_LENGTH 317 -#define AVG_PULSE_LENGTH 312 -#define RAW_LENGTH 50 - -static int validate(void) { - if(mumbi->rawlen == RAW_LENGTH) { - if(mumbi->raw[mumbi->rawlen-1] >= (MIN_PULSE_LENGTH*PULSE_DIV) && - mumbi->raw[mumbi->rawlen-1] <= (MAX_PULSE_LENGTH*PULSE_DIV)) { - return 0; - } - } - - return -1; -} - -static void createMessage(int systemcode, int unitcode, int state) { - mumbi->message = json_mkobject(); - json_append_member(mumbi->message, "systemcode", json_mknumber(systemcode, 0)); - json_append_member(mumbi->message, "unitcode", json_mknumber(unitcode, 0)); - if(state == 1) { - json_append_member(mumbi->message, "state", json_mkstring("on")); - } else { - json_append_member(mumbi->message, "state", json_mkstring("off")); - } -} - -static void parseCode(void) { - int binary[RAW_LENGTH/4], x = 0, i = 0; - - if(mumbi->rawlen>RAW_LENGTH) { - logprintf(LOG_ERR, "mumbi: parsecode - invalid parameter passed %d", mumbi->rawlen); - return; - } - - for(x=0;xrawlen-2;x+=4) { - if(mumbi->raw[x+3] > (int)((double)AVG_PULSE_LENGTH*((double)PULSE_MULTIPLIER/2))) { - binary[i++] = 1; - } else { - binary[i++] = 0; - } - } - - int systemcode = binToDec(binary, 0, 4); - int unitcode = binToDec(binary, 5, 9); - int state = binary[11]; - if(unitcode > 0) { - createMessage(systemcode, unitcode, state); - } -} - -static void createLow(int s, int e) { - int i; - - for(i=s;i<=e;i+=4) { - mumbi->raw[i]=(AVG_PULSE_LENGTH); - mumbi->raw[i+1]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - mumbi->raw[i+2]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - mumbi->raw[i+3]=(AVG_PULSE_LENGTH); - } -} - -static void createHigh(int s, int e) { - int i; - - for(i=s;i<=e;i+=4) { - mumbi->raw[i]=(AVG_PULSE_LENGTH); - mumbi->raw[i+1]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - mumbi->raw[i+2]=(AVG_PULSE_LENGTH); - mumbi->raw[i+3]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - } -} -static void clearCode(void) { - createLow(0,47); -} - -static void createSystemCode(int systemcode) { - int binary[255]; - int length = 0; - int i=0, x=0; - - length = decToBinRev(systemcode, binary); - for(i=0;i<=length;i++) { - if(binary[i]==1) { - x=i*4; - createHigh(x, x+3); - } - } -} - -static void createUnitCode(int unitcode) { - int binary[255]; - int length = 0; - int i=0, x=0; - - length = decToBinRev(unitcode, binary); - for(i=0;i<=length;i++) { - if(binary[i]==1) { - x=i*4; - createHigh(20+x, 20+x+3); - } - } -} - -static void createState(int state) { - if(state == 0) { - createHigh(44, 47); - } else { - createHigh(40, 43); - } -} - -static void createFooter(void) { - mumbi->raw[48]=(AVG_PULSE_LENGTH); - mumbi->raw[49]=(PULSE_DIV*AVG_PULSE_LENGTH); -} - -static int createCode(struct JsonNode *code) { - int systemcode = -1; - int unitcode = -1; - int state = -1; - double itmp = 0; - - if(json_find_number(code, "systemcode", &itmp) == 0) - systemcode = (int)round(itmp); - if(json_find_number(code, "unitcode", &itmp) == 0) - unitcode = (int)round(itmp); - if(json_find_number(code, "off", &itmp) == 0) - state=0; - else if(json_find_number(code, "on", &itmp) == 0) - state=1; - - if(systemcode == -1 || unitcode == -1 || state == -1) { - logprintf(LOG_ERR, "mumbi: insufficient number of arguments"); - return EXIT_FAILURE; - } else if(systemcode > 31 || systemcode < 0) { - logprintf(LOG_ERR, "mumbi: invalid systemcode range"); - return EXIT_FAILURE; - } else if(unitcode > 31 || unitcode < 0) { - logprintf(LOG_ERR, "mumbi: invalid unitcode range"); - return EXIT_FAILURE; - } else { - createMessage(systemcode, unitcode, state); - clearCode(); - createSystemCode(systemcode); - createUnitCode(unitcode); - createState(state); - createFooter(); - mumbi->rawlen = RAW_LENGTH; - } - return EXIT_SUCCESS; -} - -static void printHelp(void) { - printf("\t -s --systemcode=systemcode\tcontrol a device with this systemcode\n"); - printf("\t -u --unitcode=unitcode\t\tcontrol a device with this unitcode\n"); - printf("\t -t --on\t\t\tsend an on signal\n"); - printf("\t -f --off\t\t\tsend an off signal\n"); -} - -#if !defined(MODULE) && !defined(_WIN32) -__attribute__((weak)) -#endif -void mumbiInit(void) { - - protocol_register(&mumbi); - protocol_set_id(mumbi, "mumbi"); - protocol_device_add(mumbi, "mumbi", "Mumbi Switches"); - mumbi->devtype = SWITCH; - mumbi->hwtype = RF433; - mumbi->minrawlen = RAW_LENGTH; - mumbi->maxrawlen = RAW_LENGTH; - mumbi->maxgaplen = MAX_PULSE_LENGTH*PULSE_DIV; - mumbi->mingaplen = MIN_PULSE_LENGTH*PULSE_DIV; - - options_add(&mumbi->options, "s", "systemcode", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, "^(3[012]?|[012][0-9]|[0-9]{1})$"); - options_add(&mumbi->options, "u", "unitcode", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, "^(3[012]?|[012][0-9]|[0-9]{1})$"); - options_add(&mumbi->options, "t", "on", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); - options_add(&mumbi->options, "f", "off", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); - - options_add(&mumbi->options, "0", "readonly", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)0, "^[10]{1}$"); - options_add(&mumbi->options, "0", "confirm", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)0, "^[10]{1}$"); - - mumbi->parseCode=&parseCode; - mumbi->createCode=&createCode; - mumbi->printHelp=&printHelp; - mumbi->validate=&validate; -} - -#if defined(MODULE) && !defined(_WIN32) -void compatibility(struct module_t *module) { - module->name = "mumbi"; - module->version = "2.4"; - module->reqversion = "6.0"; - module->reqcommit = "84"; -} - -void init(void) { - mumbiInit(); -} -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/mumbi.h b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/mumbi.h deleted file mode 100644 index 5ca74e2f..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/mumbi.h +++ /dev/null @@ -1,27 +0,0 @@ -/* - Copyright (C) 2014 CurlyMo - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#ifndef _PROTOCOL_MUMBI_H_ -#define _PROTOCOL_MUMBI_H_ - -#include "../protocol.h" - -struct protocol_t *mumbi; -void mumbiInit(void); - -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/ninjablocks_weather.c b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/ninjablocks_weather.c deleted file mode 100644 index e19d7f7a..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/ninjablocks_weather.c +++ /dev/null @@ -1,246 +0,0 @@ -/* - Copyright (C) 2014 CurlyMo & wo_rasp - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#include -#include -#include -#include - -#include "../../core/pilight.h" -#include "../../core/common.h" -#include "../../core/dso.h" -#include "../../core/log.h" -#include "../protocol.h" -#include "../../core/binary.h" -#include "../../core/gc.h" -#include "ninjablocks_weather.h" - -#define PULSE_MULTIPLIER 2 -#define MIN_PULSE_LENGTH 2115 -#define MAX_PULSE_LENGTH 2125 -#define AVG_PULSE_LENGTH 2120 -#define MIN_RAW_LENGTH 41 -#define MAX_RAW_LENGTH 70 -#define RAW_LENGTH 50 - -#define PULSE_NINJA_WEATHER_SHORT 1000 -#define PULSE_NINJA_WEATHER_LONG 2000 -#define PULSE_NINJA_WEATHER_FOOTER AVG_PULSE_LENGTH // 72080/PULSE_DIV -#define PULSE_NINJA_WEATHER_LOWER 750 // SHORT*0,75 -#define PULSE_NINJA_WEATHER_UPPER 1250 // SHORT * 1,25 - -typedef struct settings_t { - double id; - double unit; - double temp; - double humi; - struct settings_t *next; -} settings_t; - -static struct settings_t *settings = NULL; - -static int validate(void) { - if(ninjablocks_weather->rawlen >= MIN_RAW_LENGTH && ninjablocks_weather->rawlen <= MAX_RAW_LENGTH) { - if(ninjablocks_weather->raw[ninjablocks_weather->rawlen-1] >= (MIN_PULSE_LENGTH*PULSE_DIV) && - ninjablocks_weather->raw[ninjablocks_weather->rawlen-1] <= (MAX_PULSE_LENGTH*PULSE_DIV)) { - return 0; - } - } - - return -1; -} - -static void createMessage(int id, int unit, double temperature, double humidity) { - ninjablocks_weather->message = json_mkobject(); - json_append_member(ninjablocks_weather->message, "id", json_mknumber(id, 0)); - json_append_member(ninjablocks_weather->message, "unit", json_mknumber(unit, 0)); - json_append_member(ninjablocks_weather->message, "temperature", json_mknumber(temperature/100, 2)); - json_append_member(ninjablocks_weather->message, "humidity", json_mknumber(humidity, 0)); -} - -static void parseCode(void) { - int x = 0, pRaw = 0, binary[MAX_RAW_LENGTH/2]; - int iParity = 1, iParityData = -1; // init for even parity - int iHeaderSync = 12; // 1100 - int iDataSync = 6; // 110 - double temp_offset = 0.0; - double humi_offset = 0.0; - - if(ninjablocks_weather->rawlen>MAX_RAW_LENGTH) { - logprintf(LOG_ERR, "ninjablocks_weather: parsecode - invalid parameter passed %d", ninjablocks_weather->rawlen); - return; - } - - // Decode Biphase Mark Coded Differential Manchester (BMCDM) pulse stream into binary - for(x=0; x<=(MAX_RAW_LENGTH/2); x++) { - if(ninjablocks_weather->raw[pRaw] > PULSE_NINJA_WEATHER_LOWER && - ninjablocks_weather->raw[pRaw] < PULSE_NINJA_WEATHER_UPPER) { - binary[x] = 1; - iParityData = iParity; - iParity = -iParity; - pRaw++; - } else { - binary[x] = 0; - } - pRaw++; - } - if(iParityData < 0) { - iParityData = 0; - } - - // Binary record: 0-3 sync0, 4-7 unit, 8-9 id, 10-12 sync1, 13-19 humidity, 20-34 temperature, 35 even par, 36 footer - int headerSync = binToDecRev(binary, 0,3); - int unit = binToDecRev(binary, 4,7); - int id = binToDecRev(binary, 8,9); - int dataSync = binToDecRev(binary, 10,12); - double humidity = binToDecRev(binary, 13,19); // % - double temperature = binToDecRev(binary, 20,34); - // ((temp * (100 / 128)) - 5000) * 10 °C, 2 digits - temperature = ((int)((double)(temperature * 0.78125)) - 5000); - - struct settings_t *tmp = settings; - while(tmp) { - if(fabs(tmp->id-id) < EPSILON && fabs(tmp->unit-unit) < EPSILON) { - humi_offset = tmp->humi; - temp_offset = tmp->temp; - break; - } - tmp = tmp->next; - } - - temperature += temp_offset; - humidity += humi_offset; - - if(iParityData == 0 && (iHeaderSync == headerSync || dataSync == iDataSync)) { - createMessage(id, unit, temperature, humidity); - } -} - -static int checkValues(struct JsonNode *jvalues) { - struct JsonNode *jid = NULL; - - if((jid = json_find_member(jvalues, "id"))) { - struct settings_t *snode = NULL; - struct JsonNode *jchild = NULL; - struct JsonNode *jchild1 = NULL; - double unit = -1, id = -1; - int match = 0; - - jchild = json_first_child(jid); - while(jchild) { - jchild1 = json_first_child(jchild); - while(jchild1) { - if(strcmp(jchild1->key, "unit") == 0) { - unit = jchild1->number_; - } - if(strcmp(jchild1->key, "id") == 0) { - id = jchild1->number_; - } - jchild1 = jchild1->next; - } - jchild = jchild->next; - } - - struct settings_t *tmp = settings; - while(tmp) { - if(fabs(tmp->id-id) < EPSILON && fabs(tmp->unit-unit) < EPSILON) { - match = 1; - break; - } - tmp = tmp->next; - } - - if(match == 0) { - if((snode = MALLOC(sizeof(struct settings_t))) == NULL) { - fprintf(stderr, "out of memory\n"); - exit(EXIT_FAILURE); - } - snode->id = id; - snode->unit = unit; - snode->temp = 0; - snode->humi = 0; - - json_find_number(jvalues, "temperature-offset", &snode->temp); - json_find_number(jvalues, "humidity-offset", &snode->humi); - - snode->next = settings; - settings = snode; - } - } - return 0; -} - -static void gc(void) { - struct settings_t *tmp = NULL; - while(settings) { - tmp = settings; - settings = settings->next; - FREE(tmp); - } - if(settings != NULL) { - FREE(settings); - } -} - -#if !defined(MODULE) && !defined(_WIN32) -__attribute__((weak)) -#endif -void ninjablocksWeatherInit(void) { - - protocol_register(&ninjablocks_weather); - protocol_set_id(ninjablocks_weather, "ninjablocks_weather"); - protocol_device_add(ninjablocks_weather, "ninjablocks_weather", "Ninjablocks Weather Sensors"); - ninjablocks_weather->devtype = WEATHER; - ninjablocks_weather->hwtype = RF433; - ninjablocks_weather->minrawlen = MIN_RAW_LENGTH; - ninjablocks_weather->maxrawlen = MAX_RAW_LENGTH; - ninjablocks_weather->mingaplen = MIN_PULSE_LENGTH*PULSE_DIV; - ninjablocks_weather->maxgaplen = MAX_PULSE_LENGTH*PULSE_DIV; - - // sync-id[4]; Homecode[4], Channel Code[2], Sync[3], Humidity[7], Temperature[15], Footer [1] - options_add(&ninjablocks_weather->options, "u", "unit", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, "^([0-9]|1[0-5])$"); - options_add(&ninjablocks_weather->options, "i", "id", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, "^([0-3])$"); - options_add(&ninjablocks_weather->options, "t", "temperature", OPTION_HAS_VALUE, DEVICES_VALUE, JSON_NUMBER, NULL, "^[0-9]{1,5}$"); - options_add(&ninjablocks_weather->options, "h", "humidity", OPTION_HAS_VALUE, DEVICES_VALUE, JSON_NUMBER, NULL, "^[0-9]{1,5}$"); - - // options_add(&ninjablocks_weather->options, "0", "decimals", OPTION_HAS_VALUE, DEVICES_SETTING, JSON_NUMBER, (void *)2, "[0-9]"); - options_add(&ninjablocks_weather->options, "0", "temperature-decimals", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)2, "[0-9]"); - options_add(&ninjablocks_weather->options, "0", "humidity-decimals", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)2, "[0-9]"); - options_add(&ninjablocks_weather->options, "0", "readonly", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)0, "^[10]{1}$"); - options_add(&ninjablocks_weather->options, "0", "show-humidity", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)1, "^[10]{1}$"); - options_add(&ninjablocks_weather->options, "0", "show-temperature", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)1, "^[10]{1}$"); - - ninjablocks_weather->parseCode=&parseCode; - ninjablocks_weather->checkValues=&checkValues; - ninjablocks_weather->validate=&validate; - ninjablocks_weather->gc=&gc; -} - -#if defined(MODULE) && !defined(_WIN32) -void compatibility(struct module_t *module) { - module->name = "ninjablocks_weather"; - module->version = "1.2"; - module->reqversion = "7.0"; - module->reqcommit = "84"; -} - -void init(void) { - ninjablocksWeatherInit(); -} -#endif - diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/ninjablocks_weather.h b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/ninjablocks_weather.h deleted file mode 100644 index 0ccc1164..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/ninjablocks_weather.h +++ /dev/null @@ -1,28 +0,0 @@ -/* - Copyright (C) 2014 CurlyMo & wo-rasp - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#ifndef _PROTOCOL_NINJABLOCKS_WEATHER_H_ -#define _PROTOCOL_NINJABLOCKS_WEATHER_H_ - -#include "../protocol.h" - -struct protocol_t *ninjablocks_weather; -void ninjablocksWeatherInit(void); - -#endif - diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/pollin.c b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/pollin.c deleted file mode 100644 index e9113927..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/pollin.c +++ /dev/null @@ -1,230 +0,0 @@ -/* - Copyright (C) 2014 CurlyMo - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#include -#include -#include -#include - -#include "../../core/pilight.h" -#include "../../core/common.h" -#include "../../core/dso.h" -#include "../../core/log.h" -#include "../protocol.h" -#include "../../core/binary.h" -#include "../../core/gc.h" -#include "pollin.h" - -#define PULSE_MULTIPLIER 3 -#define MIN_PULSE_LENGTH 296 -#define MAX_PULSE_LENGTH 306 -#define AVG_PULSE_LENGTH 301 -#define RAW_LENGTH 50 - -static int validate(void) { - if(pollin->rawlen == RAW_LENGTH) { - if(pollin->raw[pollin->rawlen-1] >= (MIN_PULSE_LENGTH*PULSE_DIV) && - pollin->raw[pollin->rawlen-1] <= (MAX_PULSE_LENGTH*PULSE_DIV)) { - return 0; - } - } - - return -1; -} - -static void createMessage(int systemcode, int unitcode, int state) { - pollin->message = json_mkobject(); - json_append_member(pollin->message, "systemcode", json_mknumber(systemcode, 0)); - json_append_member(pollin->message, "unitcode", json_mknumber(unitcode, 0)); - if(state == 0) { - json_append_member(pollin->message, "state", json_mkstring("on")); - } else { - json_append_member(pollin->message, "state", json_mkstring("off")); - } -} - -static void parseCode(void) { - int binary[RAW_LENGTH/4], x = 0, i = 0; - - if(pollin->rawlen>RAW_LENGTH) { - logprintf(LOG_ERR, "pollin: parsecode - invalid parameter passed %d", pollin->rawlen); - return; - } - - for(x=0;xrawlen-2;x+=4) { - if(pollin->raw[x+3] > (int)((double)AVG_PULSE_LENGTH*((double)PULSE_MULTIPLIER/2))) { - binary[i++] = 1; - } else { - binary[i++] = 0; - } - } - - int systemcode = binToDec(binary, 0, 4); - int unitcode = binToDec(binary, 5, 9); - int state = binary[11]; - createMessage(systemcode, unitcode, state); -} - -static void createLow(int s, int e) { - int i; - - for(i=s;i<=e;i+=4) { - pollin->raw[i]=(AVG_PULSE_LENGTH); - pollin->raw[i+1]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - pollin->raw[i+2]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - pollin->raw[i+3]=(AVG_PULSE_LENGTH); - } -} - -static void createHigh(int s, int e) { - int i; - - for(i=s;i<=e;i+=4) { - pollin->raw[i]=(AVG_PULSE_LENGTH); - pollin->raw[i+1]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - pollin->raw[i+2]=(AVG_PULSE_LENGTH); - pollin->raw[i+3]=(PULSE_MULTIPLIER*AVG_PULSE_LENGTH); - } -} -static void clearCode(void) { - createLow(0,47); -} - -static void createSystemCode(int systemcode) { - int binary[255]; - int length = 0; - int i=0, x=0; - - length = decToBinRev(systemcode, binary); - for(i=0;i<=length;i++) { - if(binary[i]==1) { - x=i*4; - createHigh(x, x+3); - } - } -} - -static void createUnitCode(int unitcode) { - int binary[255]; - int length = 0; - int i=0, x=0; - - length = decToBinRev(unitcode, binary); - for(i=0;i<=length;i++) { - if(binary[i]==1) { - x=i*4; - createHigh(20+x, 20+x+3); - } - } -} - -static void createState(int state) { - if(state == 1) { - createHigh(44, 47); - } -} - -static void createFooter(void) { - pollin->raw[48]=(AVG_PULSE_LENGTH); - pollin->raw[49]=(PULSE_DIV*AVG_PULSE_LENGTH); -} - -static int createCode(struct JsonNode *code) { - int systemcode = -1; - int unitcode = -1; - int state = -1; - double itmp = -1; - - if(json_find_number(code, "systemcode", &itmp) == 0) - systemcode = (int)round(itmp); - if(json_find_number(code, "unitcode", &itmp) == 0) - unitcode = (int)round(itmp); - if(json_find_number(code, "off", &itmp) == 0) - state=1; - else if(json_find_number(code, "on", &itmp) == 0) - state=0; - - if(systemcode == -1 || unitcode == -1 || state == -1) { - logprintf(LOG_ERR, "pollin: insufficient number of arguments"); - return EXIT_FAILURE; - } else if(systemcode > 31 || systemcode < 0) { - logprintf(LOG_ERR, "pollin: invalid systemcode range"); - return EXIT_FAILURE; - } else if(unitcode > 31 || unitcode < 0) { - logprintf(LOG_ERR, "pollin: invalid unitcode range"); - return EXIT_FAILURE; - } else { - createMessage(systemcode, unitcode, state); - clearCode(); - createSystemCode(systemcode); - createUnitCode(unitcode); - createState(state); - createFooter(); - pollin->rawlen = RAW_LENGTH; - } - return EXIT_SUCCESS; -} - -static void printHelp(void) { - printf("\t -s --systemcode=systemcode\tcontrol a device with this systemcode\n"); - printf("\t -u --unitcode=unitcode\t\tcontrol a device with this unitcode\n"); - printf("\t -t --on\t\t\tsend an on signal\n"); - printf("\t -f --off\t\t\tsend an off signal\n"); -} - -#if !defined(MODULE) && !defined(_WIN32) -__attribute__((weak)) -#endif -void pollinInit(void) { - - protocol_register(&pollin); - protocol_set_id(pollin, "pollin"); - protocol_device_add(pollin, "pollin", "Pollin Switches"); - pollin->devtype = SWITCH; - pollin->hwtype = RF433; - pollin->minrawlen = RAW_LENGTH; - pollin->maxrawlen = RAW_LENGTH; - pollin->maxgaplen = MAX_PULSE_LENGTH*PULSE_DIV; - pollin->mingaplen = MIN_PULSE_LENGTH*PULSE_DIV; - - options_add(&pollin->options, "s", "systemcode", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, "^(3[012]?|[012][0-9]|[0-9]{1})$"); - options_add(&pollin->options, "u", "unitcode", OPTION_HAS_VALUE, DEVICES_ID, JSON_NUMBER, NULL, "^(3[012]?|[012][0-9]|[0-9]{1})$"); - options_add(&pollin->options, "t", "on", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); - options_add(&pollin->options, "f", "off", OPTION_NO_VALUE, DEVICES_STATE, JSON_STRING, NULL, NULL); - - options_add(&pollin->options, "0", "readonly", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)0, "^[10]{1}$"); - options_add(&pollin->options, "0", "confirm", OPTION_HAS_VALUE, GUI_SETTING, JSON_NUMBER, (void *)0, "^[10]{1}$"); - - pollin->parseCode=&parseCode; - pollin->createCode=&createCode; - pollin->printHelp=&printHelp; - pollin->validate=&validate; -} - -#if defined(MODULE) && !defined(_WIN32) -void compatibility(struct module_t *module) { - module->name = "pollin"; - module->version = "2.4"; - module->reqversion = "6.0"; - module->reqcommit = "84"; -} - -void init(void) { - pollinInit(); -} -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/pollin.h b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/pollin.h deleted file mode 100644 index 2707d453..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/pollin.h +++ /dev/null @@ -1,27 +0,0 @@ -/* - Copyright (C) 2014 CurlyMo - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ - -#ifndef _PROTOCOL_POLLIN_H_ -#define _PROTOCOL_POLLIN_H_ - -#include "../protocol.h" - -struct protocol_t *pollin; -void pollinInit(void); - -#endif diff --git a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/quigg_gt1000.c b/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/quigg_gt1000.c deleted file mode 100644 index 2858a2fe..00000000 --- a/lib/ESPiLight/src/pilight/libs/pilight/protocols/433.92/quigg_gt1000.c +++ /dev/null @@ -1,430 +0,0 @@ -/* - Copyright (C) 2015 CurlyMo & wo_rasp & RvW - - This file is part of pilight. - - pilight is free software: you can redistribute it and/or modify it under the - terms of the GNU General Public License as published by the Free Software - Foundation, either version 3 of the License, or (at your option) any later - version. - - pilight is distributed in the hope that it will be useful, but WITHOUT ANY - WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - A PARTICULAR PURPOSE. See the GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with pilight. If not, see -*/ -/* Protocol quigg_gt1000 is an implementation of a protocol for the Quigg GT-FSI-08 switches - with GT-1000 remote. It is believed that they are compatible with the Lidl and Brennenstuhl outlets - RvW, jan 2015 - This implementation mimics the GT-1000 remote control with extensions - These switches listen to the next command string of 24 bit: - |-|0-----------4|5---------20|21------24| - |S| group-id[4] | random[16] |unit-id[4]| - |-|-------------|------------|----------| - where: - S=Start, a short high pulse of 350 us followed by a low of 2350 us - group-id[4]= 4 logic bits for the group-id code, range 0..15 - unit-id[4]= 4 bits for the unit code for switches 1..4. Two different coding schemes are used - random[16]= a 16 bit sequence where no bits seems to have a specific function. Each action - for each switch uses 4 codes (40 in total for one group-id) that are transmitted in a rolling sequence by the RC - Although codes are reused within a single group, for the sake of code simplicity and readability - this implementation will not use this fact. So we will implement a table with 16*40 = 640 "random" codes - - A logic bit is encoded by the position of the high to low transition in the 1540 us bit window. - A logic 1 therefore is encoded by a mark(high) of 1100 us followed by a space(low) of 440 us. - A logic 0 is encoded by a mark of 330 us followed by a space of 1210 us - - The total message consists of 24 bit + start pulse, and has therefore a duration 39660 us - There is no space between the repetition of a message, so the next message immediately follows the previous message - - To program a switch the RC uses a second type of start pulse with a mark(high) of 3000us and a space(low) of 7300us - In order to be able to program switches from pilight, this implementation mimics this behavior by - transmitting two normal code sequences followed by a program sequence with this long start pulse. - This implies that the complete message in fact consists of 75 bits and a short footer. -*/ - -#include -#include -#include -#include - -#include "../../core/pilight.h" -#include "../../core/common.h" -#include "../../core/dso.h" -#include "../../core/log.h" -#include "../protocol.h" -#include "../../core/binary.h" -#include "../../core/gc.h" -#include "quigg_gt1000.h" - -/* define the basic protocol Mark-Space pulse width and other values*/ -#define START_MARK 350 -#define START_SPACE 2340 -#define PROG_MARK 3000 -#define PROG_SPACE 7300 -#define SHORT_MARK 330 -#define LONG_SPACE 1210 -#define LONG_MARK 1100 -#define SHORT_SPACE 440 -#define FOOTER_MARK 200 - -#define LEARN_REPEATS 40 -#define NORMAL_REPEATS 10 -#define PULSE_MULTIPLIER 2 -#define MIN_PULSE_LENGTH 320 -#define MAX_PULSE_LENGTH 340 -#define AVG_PULSE_LENGTH 330 -#define RAW_LENGTH 151 -#define BIN_LENGTH 24 -/* -// Support Rx -static int validate(void) { - if(quigg_gt1000->rawlen == RAW_LENGTH) { - if(quigg_gt1000->raw[0] >= (int)(START_MARK*0.9) && - quigg_gt1000->raw[0] <= (int)(START_MARK*1.1) && - quigg_gt1000->raw[1] >= (int)(START_SPACE*0.9) && - quigg_gt1000->raw[1] <= (int)(START_SPACE*1.1)) { - return 0; - } - } - return -1; -} -*/ -int codetab[16][40] = { - /* the next table contains the random codes (bits 4..19) of the 4 code sequences for - * each off-on action for each switch 0..3 in each group-id 0..15. - * For each group-id a separate array is created where de codes are stored in the next order: - * off-codes 0..3 for switch 0, on-codes 0..3 for switch 0, - * off-codes 0..3 for switch 1, on-codes 0..3 for switch 1, - * off-codes 0..3 for switch 2, on-codes 0..3 for switch 2, - * off-codes 0..3 for switch 3, on-codes 0..3 for switch 3, - * off-codes 0..3 for all, on-codes 0..3 for all - * If a code is unknown 0 is substituted, f.e. for group-id 0 no codes are known, so all 40 values are 0 - */ - /* code 0 */ - { 0xBB42,0x4301,0x00F9,0x8EBA, 0xE4C3,0x1924,0x6CDB,0x9D57, - 0x00F9,0x4301,0x00F9,0x8EBA, 0x9D57,0xE4C3,0x6CDB,0x1924, - 0x8EBA,0x00F9,0x4301,0xBB42, 0x1924,0xE4C3,0x6CDB,0x9D57, - 0xE4C3,0x1924,0x9D57,0x6CDB, 0x8EBA,0xBB42,0x4301,0x00F9, - 0xE4C3,0x1924,0x9D57,0x6CDB, 0x4301,0x00F9,0x8EBA,0xBB42 }, - /* code 1 */ - { 0x616A,0xCF71,0x7AE2,0xB639, 0xF59B,0xE923,0x14C4,0x32A7, - 0x616A,0xB639,0xCF71,0x7AE2, 0x14C4,0x32A7,0xF59B,0xE923, - 0xCF71,0x616A,0x7AE2,0xB639, 0xE923,0xF59B,0x14C4,0x32A7, - 0x14C4,0xE923,0xF59B,0x32A7, 0x7AE2,0x616A,0xCF71,0xB639, - 0x14C4,0xE923,0xF59B,0x32A7, 0x7AE2,0x616A,0xB639,0xCF71 }, - /* code 2 */ - { 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0 }, - /* code 3 */ - { 0x32D7,0x7D4B,0x9482,0xC818, 0x067A,0x2901,0xB1B6,0xEA35, - 0x5B5C,0x6364,0x85F9,0xFEED, 0x1FA0,0x4CCF,0xA793,0xD02E, - 0x067A,0x2901,0xB1B6,0xEA35, 0x32D7,0x7D4B,0x9482,0xC818, - 0x1FA0,0x4CCF,0xA793,0xD02E, 0x5B5C,0x6364,0x85F9,0xFEED, - 0x067A,0x2901,0xB1B6,0xEA35, 0x32D7,0x7D4B,0x9482,0xC818 }, - /* code 4 */ - { 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0 }, - /* code 5 */ - { 0x23C2,0x71A1,0x88DA,0xDC19, 0x1FBB,0x39E4,0xA743,0xFE77, - 0x23C2,0x71A1,0x88DA,0xDC19, 0x1FBB,0x39E4,0xA743,0xFE77, - 0x23C2,0x71A1,0x88DA,0xDC19, 0x1FBB,0x39E4,0xA743,0xFE77, - 0x1FBB,0x39E4,0xA743,0xFE77, 0x23C2,0x71A1,0x88DA,0xDC19, - 0x1FBB,0x39E4,0xA743,0xFE77, 0x23C2,0x71A1,0x88DA,0xDC19 }, - /* code 6 */ - { 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0 }, - /* code 7 */ - { 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0 }, - /* code 8 */ - { 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0 }, - /* code 9 */ - { 0x1B1A,0x27D9,0x75C1,0xC0A2, 0x02FB,0x3D03,0x6EE7,0xB974, - 0x1B1A,0x27D9,0x75C1,0xC0A2, 0x02FB,0x3D03,0x6EE7,0xB974, - 0x1B1A,0x27D9,0x75C1,0xC0A2, 0x02FB,0x3D03,0x6EE7,0xB974, - 0x02FB,0x3D03,0x6EE7,0xB974, 0x1B1A,0x27D9,0x75C1,0xC0A2, - 0x02FB,0x3D03,0x6EE7,0xB974, 0x1B1A,0x27D9,0x75C1,0xC0A2 }, - /* code 10 */ - { 0x9E98,0xC2AB,0xE057,0xF4F2, 0x460A,0x6971,0x77E6,0xBB25, - 0x0CBD,0x1589,0x51C4,0x8FDC, 0x2313,0x386F,0xAD3E,0xDA40, - 0x460A,0x6971,0x77E6,0xBB25, 0x9E98,0xC2AB,0xE057,0xF4F2, - 0x2313,0x386F,0xAD3E,0xDA40, 0x0CBD,0x1589,0x51C4,0x8FDC, - 0x460A,0x6971,0x77E6,0xBB25, 0x9E98,0xC2AB,0xE057,0xF4F2 }, - /* code 11 */ - { 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0 }, - /* code 12 */ - { 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0 }, - /* code 13 */ - { 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0 }, - /* code 14 */ - { 0xE692,0x98F8,0x577B,0xABB7, 0x0AD6,0xBDA1,0xC465,0x6F4A, - 0xF234,0x89EC,0x2519,0x715D, 0x1383,0xDC2F,0x40CE,0x3E00, - 0x0AD6,0xBDA1,0xC465,0x6F4A, 0xE692,0x98F8,0x577B,0xABB7, - 0x1383,0xDC2F,0x40CE,0x3E00, 0xF234,0x89EC,0x2519,0x715D, - 0x0AD6,0xBDA1,0xC465,0x6F4A, 0xE692,0x98F8,0x577B,0xABB7 }, - /* code 15 */ - { 0x1067,0x3D02,0x9B1B,0, 0x2636,0x6C81,0xE5B5,0xF1FA, - 0x432D,0x54CC,0x8A79,0xC7D4, 0x7290,0xA85F,0xDFEE,0, - 0x2636,0x6C81,0xE5B5,0xF1FA, 0x1067,0x3D02,0x9B1B,0, - 0x7290,0xA85F,0xDFEE,0, 0x432D,0x54CC,0x8A79,0xC7D4, - 0x2636,0x6C81,0xE5B5,0xF1FA, 0x1067,0x3D02,0x9B1B,0 } -}; - -int unittab[2][5] = { - /* This table defines the coding of the unit-id or switch-id. Two coding schemes are used - * I call them first and second generation switches. They encode the unit-id in a different way. - */ - /* first gen group-id = 1, 5, 9, 12 */ - { 0x0, 0x4, 0xC, 0x2, 0xA }, /* these are 1st gen switch-codes for switch 0..3 and all */ - /* second gen all other */ - { 0xC, 0x5, 0xE, 0x7, 0x2 } /* 2nd gen switch-codes */ -}; - -int gentab[16] = - /* This table defines the switch generation for each group-id - * A 0 at location x means group-id x belongs to first generation, and a 1 means second generation - */ - /* for now only group-id 1,5,9 and 12 are first generation */ - {0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1}; - -#define NRSUPERMASK 0x07 -#define NRSUPERCODES (NRSUPERMASK+1) /* we will use 8 on and 8 off supercodes */ -/* make sure the number of Supercodes is always a power of 2, i.e. 2,4,8,16 ... */ -int supercodes[2*NRSUPERCODES] = { - /* since with supercodes group-id's are irrelevant, the codes consist of the first 20 bits of the code sequence */ - /* OFF codes */ - 0x0F000,0x1F006,0x4F00E,0x5F016,0x8F01E,0x9F026,0xCF02E,0xDF02F, - /* ON codes */ - 0x0F005,0x1F008,0x4F015,0x5F018,0x8F025,0x9F028,0xCF02C,0xDF03C }; - -char bincode[BIN_LENGTH+1]; - -static void createMessage(int id, int unit, int state, int seq, int learn) { - int i = 0; - - for(i=0;imessage = json_mkobject(); - json_append_member(quigg_gt1000->message, "id", json_mknumber(id, 0)); - json_append_member(quigg_gt1000->message, "unit", json_mknumber(unit, 0)); - json_append_member(quigg_gt1000->message, "seq", json_mknumber(seq, 0)); - if(state == 1) { - json_append_member(quigg_gt1000->message, "state", json_mkstring("on")); - } else { - json_append_member(quigg_gt1000->message, "state", json_mkstring("off")); - } - json_append_member(quigg_gt1000->message, "code", json_mkstring(bincode)); -} - -static int fillLow(int idx) { - /* fill in the mark-space code for a logic Low = short pulse*/ - quigg_gt1000->raw[idx++] = SHORT_MARK; - quigg_gt1000->raw[idx++] = LONG_SPACE; - return idx; -} - -static int fillHigh(int idx) { - /* fill in the mark-space code for a logic High = long pulse*/ - quigg_gt1000->raw[idx++] = LONG_MARK; - quigg_gt1000->raw[idx++] = SHORT_SPACE; - return idx; -} - -static void numtoBin(int idx, int num, int len) { - /* fill in bits idx to idx+len-1 for number, msb first */ - for(len--;len>=0;len--) { - bincode[idx+len] = (num & 1); /* value is lsb num */ - num = num>>1; /* shift number 1 place to right, so 2th bit becomes lsb */ - } -} - -static int fillRawCode(void) { - /* convert binary code in bincode[] to raw Mark-Space combis for this protocol */ - /* the complete RawCode consist of